I've looked up other questions including this one however I couldn't find an answer resolves my problem.
I have defined my models in the same way described in official documentation of mongoose by showing references and defining types of models as Schema.Types.ObjectId. Here they are:
story_model.js
var storySchema = new Schema({
...
candidateParts: [{ type: Schema.Types.ObjectId, ref: 'StoryPart'}],
...
}, { usePushEach: true});
storyPart_model.js
var storyPartSchema = new Schema({
...
storyId: { type:Schema.Types.ObjectId, ref: 'Story' },
...
}, { usePushEach: true});
And, I have built a query like that where ObjectID = require('mongodb').ObjectID;
and storyModel
is Story passed through storyController.js
Here is how I call populate:
StoryController.prototype.getCandidateParts = function (storyId, callback) {
var me = this;
const id = { '_id': ObjectID(storyId) };
me.storyModel.findOne(id).populate('candidateParts').exec(function(err,story) {
if (err) return callback(err, new me.ApiResponse({ success: false, extras: { message: me.ApiMessages.DB_ERROR }}));
if (story) {
return callback(err, story);
}else {
return callback(err, new me.ApiResponse({ success: false, extras : { message: me.ApiMessages.STORY_NOT_EXISTS }}));
}
});
};
Following is how I check results of my new populated story:
me.getCandidateParts(story._id, (err, populatedStory) => {
if (err) {
return;
}
if (populatedStory) {
console.log(populatedStory);
But I get this result instead of story with populated parts:
[ { _id: 5a8bfaab78798703c0760bd1,
__v: 2,
is_updated: 2018-02-20T10:38:32.620Z,
is_created: 2018-02-20T10:38:32.620Z,
candidateParts: []
... } ]
By the way, I'm sure candidateParts include in database something like that:
ObjectId("5a8bfa33cd601903b57329ab")
And yes, I'm also sure that I have defined model references with exactly the same identifiers.
Thanks in advance!