mongoose引用不起作用

我创build了两个Schema,User和Whisp(一个whisp就像一个tweet)。

//User var UserSchema = new mongoose.Schema({ username: { type: String, required: true, index: { unique: true } }, password: { type: String, required: true } }); UserModel = mongoose.model("UserSchema", UserSchema); module.exports.User = UserModel; //Whisp var WhispSchema = new mongoose.Schema({ text : String, created_at : Date, created_by : {type : Schema.Types.ObjectId, ref : "UserSchema"}//i want to ref User }); var WhispModel = mongoose.model("WhispSchema", WhispSchema); module.exports.Whisp = WhispModel; 

现在在一个明确的路线我想创造一个新的轻声。

 var whisp = new Model.Whisp(); whisp.text = req.body.text; Model.User.findOne({username: req.body.username }, function(err, userfound) { if (err) throw err; if (userfound) { console.log(userfound._id); whisp.created_by = userfound._id; } else { res.send("Wrong Username"); } }) whisp.save(function(err, whispsaved) { if (err) throw err; Model.Whisp.findOne({_id: whispsaved._id }) .populate('created_by') .exec(function(err, whispop) { if (err) return handleError(err); console.log('The creator is %s', whispop.created_by.username); }); }); 

但是我不知道为什么whispop总是undefined

您的问题与引用无关,与节点的asynchronous性质无关。

保存function必须位于Model.User.findOne函数的callback中。 像这样的东西:

 var whisp = new Model.Whisp(); whisp.text = req.body.text; Model.User.findOne({username: req.body.username}, function (err, userfound) { if (err) throw err; if (userfound) { console.log(userfound._id); whisp.created_by = userfound._id; whisp.save(function (err, whispsaved) { if (err) throw err; Model.Whisp .findOne({_id: whispsaved._id}) .populate('created_by') .exec(function (err, whispop) { if (err) return handleError(err); console.log('The creator is %s', whispop.created_by.username); }); }); } else { res.send("Wrong Username"); } }); 

否则,保存callback将在findOne完成之前执行。