Model.find() 在 Mongoose + Nodejs 中的 model.save() 之后返回 null [英] Model.find() returns null after model.save() in Mongoose + Nodejs

查看:53
本文介绍了Model.find() 在 Mongoose + Nodejs 中的 model.save() 之后返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

save 函数运行良好,但是,它下面的 find 函数在搜索先前保存的 save 对象时返回 null.代码如下:

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() 返回 null.甚至 User.find({}) 返回 null.

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

推荐答案

在您的代码中,从数据库中保存和查找数据都是异步的.

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

由于查找的结果取决于正在完成的保存,因此您必须等待 save 完成才能调用 find(或 findById>).

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.

这篇关于Model.find() 在 Mongoose + Nodejs 中的 model.save() 之后返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆