Reputation: 63
This issue seems to be common but the answers for it vary. I am trying to populate these two models with their data.
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.listen(4000,()=>{
console.log('server listening on port 4000')
});
mongoose.connect('mongodb://localhost:27017/testDB',{useNewUrlParser:true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify:true });
const UserSchema = new mongoose.Schema({
username: String,
})
const PostSchema = new mongoose.Schema({
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}
})
const Post = mongoose.model('Post', PostSchema);
const User = mongoose.model('User', UserSchema);
const user = new User({
username: 'alex antoine',
})
const posts = new Post({
content: 'I hope this works'
})
UserSchema.virtual('Post',{
localField: '_id',
foreignField: 'author',
ref:'Post',
})
const populateUser = async(username)=>{
const user = await User.findOne({username}).populate('posts');
const userPopulated = await user.populate('Post').execPopulate();
console.log(userPopulated);
}
const save = async()=>{
user.save();
posts.save();
}
save();
populateUser('alex antoine');
The response I received from this is
Populated User {
posts: [],
_id: 60dbe989fd1ab074d0ab0541,
username: 'alex antoine',
__v: 0
}
This seems to be a common issue that a lot of people had but none of their answers seems to work for me. Thanks in advance.
Upvotes: 1
Views: 159
Reputation: 354
You're not declaring your user's posts as a virtual field right. Your PostSchema is correct, but your UserSchema should look like this:
const UserSchema = new mongoose.Schema({
username: String
})
UserSchema.virtual('posts', {
ref: Posts,
localfield: '_id',
foreignField: 'author'
});
This way, when dealing with a user document, you can populate its posts:
user.populate('posts').execPopulate();
Upvotes: 1
Reputation: 1025
result User.findOne({username}).populate('posts').exec();
// At the exec() try using execPopulate()
Then at the ref
add the required: true` option
Upvotes: 0