sails.jssails-mongo

Unable to get the id of newly created record sails js


I am creating a new record like this:

  Resource.create({
    title: req.body.title,
    address: {...req.body.address},
    email: req.body.email,
  }, (err, record) =>{
    if(err){
      res.send({'status': err});
    }else{
      res.send(
        {
          'status': 'it worked',
          'data': req.body
        }
      );
      sails.log(record.title)
    }
  });

The request process perfectly and the new record is added to the database(I can see it too). But I cant get the id right when its created for some weird reason.

I've been following a tutorial and record is supposed to not be undefined, I am using MongoDB with SailsJS


Solution

  • You have to chain a "fetch" after creating the record, for example:

    let resource = Resource.create({...}).fetch();
    

    This will fetch the record you just created with its associated id.