I have a simple setup similar to the below:
const mongoose = require('mongoose');
const schema1Schema = new mongoose.Schema({
schema2Items: [
{
schema2Item: {
type: mongoose.Schema.Types.ObjectId,
ref: 'schema2s',
},
},
],
});
const schema2Schema = new mongoose.Schema({
name: {
type: String,
},
selfReferences: [
{
selfReference: {
type: mongoose.Schema.Types.ObjectId,
ref: 'schema2s',
},
},
],
});
module.exports = {
Schema1: mongoose.model('schema1s', schema1Schema),
Schema2: mongoose.model('schema2s', schema2Schema),
}
Running find
on Schema2
returns the following,
const schema2Documents = await Schema2.find().select('-_id -__v')
[
{ name: 'schema2 One', "selfReferences": [] },
{ name: 'schema2 Two', "selfReferences": [
{ "name": 'schema2 Three', "selfReferences": [] },
{ "name": 'schema2 Four', "selfReferences": [] },
] },
{ name: 'schema2 Five', "selfReferences": [] },
]
But if I run find
or findOne
and populate
on Schema1
, it returns this:
const schema2ItemsInSchema1 = await Schema1.findOne().populate('schema2Items.schema2Item').select('-_id -__v')
{
"schema2Items": [
{
"schema2Item": {
"name": "schema2 One",
"selfReferences": []
}
},
{
"schema2Item": {
"name": "schema2 Two",
"selfReferences": [
{}, // <-- is not being populated
{} // <-- is also not being populated
]
}
},
{
"schema2Item": {
"name": "schema2 Five",
"selfReferences": []
}
}
]
}
Why is the selfReferences
field in schema2Items.schema2Item
path not being populated? The expected result should be,
const schema2ItemsInSchema1 = await Schema1.findOne().populate('schema2Items.schema2Item').select('-_id -__v')
{
"schema2Items": [
{
"schema2Item": {
"name": "schema2 One",
"selfReferences": []
}
},
{
"schema2Item": {
"name": "schema2 Two",
"selfReferences": [
{ "name": 'schema2 Three', "selfReferences": [] },
{ "name": 'schema2 Four', "selfReferences": [] },
]
}
},
{
"schema2Item": {
"name": "schema2 Five",
"selfReferences": []
}
}
]
}
Edit
I've tried the following,
const schema2ItemsInSchema1 = await Schema1.findOne().populate({
path: 'schema2Items.schema2Item',
model: 'schema2s',
populate: { path: 'selfReferences', model: 'schema2s' },
}).select('-_id -__v')
But still no luck. I've also tried mongoose-autopopulate, and that didn't work either.
question from:
https://stackoverflow.com/questions/65883662/mongoose-deep-populate-is-not-returning-the-populated-document-that-has-a-ref-on