我查找了其他问题,包括 this one但是我找不到解决我问题的答案。
我已经按照 official documentation of mongoose 中描述的相同方式定义了我的模型通过显示引用并将模型类型定义为 Schema.Types.ObjectId。他们在这里:
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});
而且,我构建了一个类似这样的查询,其中 ObjectID = require('mongodb').ObjectID;
和 storyModel
是通过 storyController.js 传递的 Story
下面是我调用填充的方式:
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 }}));
}
});
};
以下是我如何检查我的新填充故事的结果:
me.getCandidateParts(story._id, (err, populatedStory) => {
if (err) {
return;
}
if (populatedStory) {
console.log(populatedStory);
但我得到的是这个结果,而不是带有填充部分的故事:
[ { _id: 5a8bfaab78798703c0760bd1,
__v: 2,
is_updated: 2018-02-20T10:38:32.620Z,
is_created: 2018-02-20T10:38:32.620Z,
candidateParts: []
... } ]
顺便说一下,我确定 candidateParts 在数据库中包含类似这样的东西:
ObjectId("5a8bfa33cd601903b57329ab")
是的,我也确定我已经使用完全相同的标识符定义了模型引用。
提前致谢!
最佳答案
我意识到不知何故我对 StoryPart 和 Story 实例具有相同的 ID。这就是为什么它什么都不返回的原因。
编辑:
我已通过确保和更正故事和故事部分的 ID 解决了这个问题。我不删除这个问题,因为可能有人面临同样的问题, 所以只需检查您的 ObjectID 是否引用了正确的实例。
关于javascript - Mongoose.populate() 返回空数组而不是数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884056/