Model.find() returns null after model.save() in Mongoose + Nodejs

寵の児 提交于 2021-01-28 06:43:13

问题


The save function works perfectly but, the find function just below it returns null on searching the save object which is previously saved. Here is the code:

var mongoose = require("mongoose");
var User = mongoose.model("User");

module.exports.register = function(req, res) {
  var user = new User();
  user.name = req.body.name;
  user.email = req.body.email;
  user.setPassword(req.body.password);
  user.save(function(err) {
    var token;
    token = user.generateJwt();
    res.status(200);
    res.json({
      token: token
    });
  });
  User.findById(user._id, function(err, particularDocument) {
    if (err) {
      console.log(err);
    } else {
      console.log(particularDocument);
    }
  });
};

User.findById() return null. Even User.find({}) returns null.


回答1:


Both saving and finding data from the db is asynchronous in your code.

Since the results of the find depend on the save being finished, you must wait for the save to finish before calling find (or findById).

At the moment, you are executing them at the same time:

// call save but don't wait for it to finish
user.save(/* callback when save is done. this is executed sometime after all other code is done executing. */);
// call findById but don't wait for it to finish
User.findById(user._id, /* callback when find is done. this is executed sometime after all other code is done executing. */);
// continue here before any of the callbacks are executed

But you should execute them serially:

user.save(function() {
  User.findById(user._id, function(err, user) {
    // get user here
  })
  // ...
});

The reason this is necessary is because asynchronous code runs some time after all the synchronous code is finished.

In other words, no asynchronous code runs until the current segment of synchronous code is finished.



来源:https://stackoverflow.com/questions/49454345/model-find-returns-null-after-model-save-in-mongoose-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!