猫鼬在填充对象上填充 returns 空数组

mongoose populate returns null array on populated object

基本上我已经创建了一个 mongo 数据库并制作了一个 Post 模型,该模型通过 _id 引用用户。 我想获取有关 post 用户的信息,因此当我填充所选用户时,我在 exec() 中创建了一个回调函数。但结果是一个空数组。 我除了 populate.exec() 帮助我获得更多关于 post 的信息,就像这样

{
  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);
    }
});

你有

   posts: [{
        type: mongoose.Schema.Types.ObjectId,
        rel: 'Post'
    }]

应该是参考中的ref,而不是rel

   posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
    }]