Search code examples
javascriptmongoosemongoose-populate

mongoose populate returns null array on populated object


Basically I have create a mongo database and have made a Post model which referenced to the User by _id. I want to get the information on the post user have so I made a callback function in exec() when I am populating the selected User. But the result is an empty array. I except populate.exec() helps me to get more info on post like this

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

However, the result is just

{
  posts: [],
  _id: 5f287adf86b8a617300122a7,
  email: 'bob@gmail.com',
  name: 'Bob',
  __v: 2
}

I am appreciate if someone who can help me with this. My js code shows below!

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

Solution

  • You have

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

    It should be ref as in reference, not rel

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