Using Schema as a Model and Subdocument causes issues with populate.
Bug but possibly something I shouldn't be doing. Mongoose 5.0.6 MongoDB 3.4.5 NodeJS 8.5.0
If I define a Schema and use it as both a Model and Subdocument it causes an issue when using populate.
For example in the following: MessageSchema is used as a Message model but also as a Subdocument of ConversationSchema under lastMessage.
const MessageSchema = new Schema({
accountId: {type: ObjectId},
authorId: {type: ObjectId},
conversationId: {type: ObjectId},
body: {type: Object},
createdAt: {type: Date},
}, {
toObject: {
virtuals: true,
},
});
MessageSchema.virtual('author', {
ref: 'User',
localField: 'authorId',
foreignField: '_id',
justOne: true,
});
module.exports.Message = mongoose.model('Message', MessageSchema);
const Conversation = new Schema({
accountId: {type: String},
authorId: {type: ObjectId},
createdAt: {type: Date},
isArchived: {type: Boolean},
lastMessage: MessageSchema,
participants: [{type: Schema.Types.ObjectId, ref: 'User'}],
}, {
toObject: {
virtuals: true,
},
});
Conversation.virtual('account', {
ref: 'Account',
localField: 'accountId',
foreignField: '_id',
justOne: true,
});
module.exports.Conversation = mongoose.model('Conversation', Conversation);
Once .populate('lastMessage.author') is called on Conversation model, .populate('author') on Message model no longer works.
If I duplicate the MessageSchema, creating one of use by the Message Model and one as a Subdocument of Conversation, the problem goes away.
Can you clarify what you mean by "no longer works"? Does some error occur? Or do you just get no documents?
In my situation, when I upgraded to Mongoose 5* my virtual populations are no longer pulling in the data. Related? (ROInfo is not retrieved)
var whiteHatSchema = new mongoose.Schema({
impact: String,
id: String
},
{ collection: 'whitehat' },
{ //Allow this schema to be used and return in virtual populations
toJSON: {virtuals:true},
toObject: {virtuals:true}
}
);
whiteHatSchema.virtual('ROInfo', {
ref: 'RO',
localField: 'id',
foreignField: 'WhiteHatID'
});
var Whitehat = mongoose.model('Whitehat', whiteHatSchema)
module.exports = Whitehat;
app.get('/api/app_findings/:appName', middleware.validate_sanitize, team_auth.uscm_auth, function (req, res) {
Whitehat.find({site_name: req.params.appName}).populate('ROInfo').exec(function (err, whitehat) {
if (err) {
console.log("Couldn't find whitehat data");
}
res.json(whitehat);
console.log(whitehat);
});
});
module.exports = app;
**When I reverted to Mongoose^4.8.4 -- The problem is gone and the virtual fields are returned like normal.
@zbornstein does whiteHadSchema even have an id property? Or is it a virtual?
@vkarpov15 Hi, yes it does. I redacted all of the schema content here, but I can confirm it does.
@zbornstein below script works fine for me. Please modify the below script to reproduce your issue.
const mongoose = require('mongoose');
mongoose.set('debug', true);
const GITHUB_ISSUE = `gh-6149`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
mongoose.Promise = global.Promise;
run().catch(error => console.error(error.stack));
async function run() {
await mongoose.connect(connectionString);
await mongoose.connection.dropDatabase();
const { Schema } = mongoose;
const whiteHatSchema = new Schema({
impact: String,
id: String
}, { toJSON: {virtuals:true}, toObject: {virtuals:true} });
whiteHatSchema.virtual('ROInfo', {
ref: 'RO',
localField: 'id',
foreignField: 'WhiteHatID'
});
const Whitehat = mongoose.model('Whitehat', whiteHatSchema);
const RO = mongoose.model('RO', new Schema({
WhiteHatID: String
}));
await Whitehat.create({ id: 'test' });
await RO.create({ WhiteHatID: 'test' });
const res = await Whitehat.find({}).populate('ROInfo');
console.log(res[0]);
}
Output:
$ node gh-6149.js
Mongoose: whitehats.insert({ _id: ObjectId("5ab91ee44b94e129a9c052f7"), id: 'test', __v: 0 })
Mongoose: ros.insert({ _id: ObjectId("5ab91ee44b94e129a9c052f8"), WhiteHatID: 'test', __v: 0 })
Mongoose: whitehats.find({}, { fields: {} })
Mongoose: ros.find({ WhiteHatID: { '$in': [ 'test' ] } }, { fields: {} })
{ _id: 5ab91ee44b94e129a9c052f7,
id: 'test',
__v: 0,
ROInfo:
[ { _id: 5ab91ee44b94e129a9c052f8, WhiteHatID: 'test', __v: 0 } ] }
^C
$