How to save object immediately in MongoDB?

1k Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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