1

In my Node application I use the mongoose module. I found out that after

model_name.create({...})

object is not created immediately but with some delay (buffer?). How can I force to save this new object in this particular moment?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
user3616181
  • 975
  • 2
  • 8
  • 27
  • 3
    mongoose is asynchronous, so the document you created can't be queried on the next line. either use the success callback function or try and make it synchronous as per this accepted answer: http://stackoverflow.com/questions/17181248/making-mongoose-js-queries-run-synchronously – caffeinated.tech Jun 09 '15 at 12:21
  • Of course! It was that easy. I used callback function and it works great. Thank you very much! – user3616181 Jun 09 '15 at 12:27

1 Answers1

1

Mongoose inserts the value inmediatly.

The problem is that you are not using it´s callback. Try to code this way:

  //There is the definition
  Customer.create(YOURDATA, function (err, obj) {
    if (err) {
      //This will be executed if create is going bad.
      return handleError(res, err);
    }
    //This code will be executed AFTER SAVE
   console.log(obj._id):
   return res.json(201, obj);
  });
  • Callback functions will be automatically executed by mongoose after the CREATE function has been executed in BD.

  • In obj, you will receive the saved object from DB, and then you will be able to access its properties.

Anyway, there you have some documentation:

Hope it will solve you problem

Community
  • 1
  • 1