1

I am using App Engine flexible environment with Node.js and am trying to store and retrieve entities in Cloud Datastore.

The following code successfully creates a new Event Entity:

/* Create event */
router.post('/', function(req, res, next) {    
  const eventKey = datastore.key('Event');
  datastore.save({
    key: eventKey,
    data: req.body
  })
  .then(() => {
    console.log('New event created');
    res.json({id: eventKey.id});
  })
  .catch((err) => { next(err); });
});

However, the following returns an empty array when I provide the previously returned id:

/* Get an event */
router.get('/:id', function(req, res, next) {
  console.log(req.params.id);
  var eventKey = datastore.key(['Event', req.params.id]);
  datastore.get(eventKey)
  .then((event) => {
    console.log(event);
    res.json(event);
  })
  .catch((err) => { console.log(err); next(err); });
});

I seem to be using datastore.get correctly and to do what the docs is telling me to do.

Any idea why I cannot get the entity I previously created?

1 Answer 1

1

It's worth noting that Cloud Datastore keys ([Ancestor path +] kind + id/name) treat integers (id) and strings (name) differently. That is to say that the following 2 keys refer to different entities:

  • Key(Event, 1234)
  • Key(Event, "1234")

I'm not a node expert, but is it possible it is writing and reading these different keys?

parseInt can solve this:

/* Get an event */
router.get('/:id', function(req, res, next) {
  console.log(req.params.id);
  var eventId = parseInt(req.params.id, 10)
  var eventKey = datastore.key(['Event', eventId]);
  datastore.get(eventKey)
  .then((event) => {
    console.log(event);
    res.json(event);
  })
  .catch((err) => { console.log(err); next(err); });
});
Sign up to request clarification or add additional context in comments.

1 Comment

That was it: making sure I was passing an integer solved it: var eventKey = datastore.key(['Event', parseInt(req.params.id, 10)]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.