-
This are my schemas: user.js 'use strict'
const { models, model, Schema } = require('mongoose')
const schema = new Schema(
{
name: {
type: String,
required: true,
},
},
{
timestamps: true,
discriminatorKey: 'type',
}
)
schema.virtual('posts', {
ref: 'Post',
localField: '_id',
foreignField: 'user',
})
module.exports = models.User|| model('User', schema) post.js 'use strict'
const { models, model, Schema } = require('mongoose')
const schema = new Schema(
{
text: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
},
{
timestamps: true,
discriminatorKey: 'type',
}
)
module.exports = models.Post|| model('Post', schema) And the Query: const user = await UserModel.findById(req.params.id).populate('posts') I don't know what i doing wrong, but populate is not returning anything I turn on my mongoose debug flag to check what is the query for virtual populate and see that on my terminal: Mongoose: users.findOne({ _id: new ObjectId("6182fce8c339b6f51c933eee") }, { projection: {} })
Mongoose: posts.find({ user: { '$in': [ new ObjectId("6182fce8c339b6f51c933eee") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: 0, limit: 10, perDocumentLimit: undefined, projection: {} }) I do the query manually again removing const posts = await PostModel.find({credential: { $in: [Types.ObjectId(req.params.id)]}}) and return the data, the terminal show Mongoose: posts.find({ user: { '$in': [ new ObjectId("6182fce8c339b6f51c933eee") ] } }, { projection: {} }) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
How are you determining that populate is not returning anything? Remember that virtuals don't end up in |
Beta Was this translation helpful? Give feedback.
-
@vkarpov15 you are absolutely right, I was not adding |
Beta Was this translation helpful? Give feedback.
How are you determining that populate is not returning anything? Remember that virtuals don't end up in
console.log()
output unless you enabletoObject: { virtuals: true }
on your schema, or doconsole.log(user.toObject({ virtuals: true }))