基本上,我已经创建了一个mongo数据库,并创建了一个_id引用到User的Post模型。
我想获取有关发布用户的信息,因此在填充所选用户时,我在exec()中做了一个回调函数。但是结果是一个空数组。
除了populate.exec()
之外,我可以帮助我获取有关此类帖子的更多信息
{
posts: [ {
_id: 5f287dd39eb82544302b974b,
title: 'It;s a good day pt.3',
content: 'Sunny on the morning and little cloudy in the evening :)',
__v: 0
}
],
_id: 5f287adf86b8a617300122a7,
email: 'bob@gmail.com',
name: 'Bob',
__v: 2
}
但是,结果只是
{
posts: [],
_id: 5f287adf86b8a617300122a7,
email: 'bob@gmail.com',
name: 'Bob',
__v: 2
}
如果有人可以帮助我,我将不胜感激。我的js代码如下所示!
let mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/blog_demo_2", {useNewUrlParser: true, useUnifiedTopology: true});
let postSchema = new mongoose.Schema({
title: String,
content: String
});
let Post = mongoose.model("Post", postSchema);
let userSchema = new mongoose.Schema({
email: String,
name: String,
posts: [{
type: mongoose.Schema.Types.ObjectId,
rel: 'Post'
}]
});
let User = mongoose.model("User", userSchema);
User.create({
email: "bob@gmail.com",
name: "Bob"
});
Post.create({
title: "It's a good day pt.3",
content: "Sunny on the morning and little cloudy in the evening :)"
}, function (err, newlyPost) {
if(err){
console.log(err);
}else{
User.findOne({email: "bob@gmail.com"}, function (err, foundUser) {
if(err){
console.log(err);
}else{
foundUser.posts.push(newlyPost);
foundUser.save();
}
})
}
});
User.findOne({email: "bob@gmail.com"}).populate("posts").exec(function (err, user) {
if(err){
console.log(err);
}else{
console.log(user);
}
});
答案 0 :(得分:1)
你有
posts: [{
type: mongoose.Schema.Types.ObjectId,
rel: 'Post'
}]
参考中应为ref
,而不是rel
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}]