Recently, I set up a mongo database and created a Post model that has a reference to the User by _id. I wanted to retrieve information about the posts a user has made, so I implemented a callback function within exec() while populating the selected User. However, the result turned out to be an empty array.
{
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: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa8a5a88aada7aba3a6e4a9a5a7">[email protected]</a>',
name: 'Bob',
__v: 2
}
Unfortunately, the actual outcome is as follows:
{
posts: [],
_id: 5f287adf86b8a617300122a7,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1838e83a1868c80888dcf828e8c">[email protected]</a>',
name: 'Bob',
__v: 2
}
I would be grateful for any assistance in resolving this issue. Here is the JavaScript code snippet:
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,
ref: 'Post'
}]
});
let User = mongoose.model("User", userSchema);
User.create({
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0929f92b0979d91999cde939f9d">[email protected]</a>",
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: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5855587a5d575b535614595557">[email protected]</a>"}, function (err, foundUser) {
if(err){
console.log(err);
}else{
foundUser.posts.push(newlyPost);
foundUser.save();
}
})
}
});
User.findOne({email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="65070a07250208040c094b060a08">[email protected]</a>"}).populate("posts").exec(function (err, user) {
if(err){
console.log(err);
}else{
console.log(user);
}
});