Yus*_* AK 5 javascript populate mongoose mongodb node.js
我查了其他问题,包括这个问题但是我找不到解决我问题的答案。
通过显示引用并将模型类型定义为Schema.Types.ObjectId,我以mongoose 的官方文档中描述的相同方式定义了我的模型。他们来了:
故事模型.js
var storySchema = new Schema({
...
candidateParts: [{ type: Schema.Types.ObjectId, ref: 'StoryPart'}],
...
}, { usePushEach: true});
Run Code Online (Sandbox Code Playgroud)
storyPart_model.js
var storyPartSchema = new Schema({
...
storyId: { type:Schema.Types.ObjectId, ref: 'Story' },
...
}, { usePushEach: true});
Run Code Online (Sandbox Code Playgroud)
而且,我已经建立了这样的一个地方查询ObjectID = require('mongodb').ObjectID;和storyModel是通过故事传递storyController.js
这是我调用 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 }}));
}
});
};
Run Code Online (Sandbox Code Playgroud)
以下是我如何检查我的新填充故事的结果:
me.getCandidateParts(story._id, (err, populatedStory) => {
if (err) {
return;
}
if (populatedStory) {
console.log(populatedStory);
Run Code Online (Sandbox Code Playgroud)
但是我得到了这个结果而不是带有填充部分的故事:
[ { _id: 5a8bfaab78798703c0760bd1,
__v: 2,
is_updated: 2018-02-20T10:38:32.620Z,
is_created: 2018-02-20T10:38:32.620Z,
candidateParts: []
... } ]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我确定候选人零件在数据库中包含类似的内容:
ObjectId("5a8bfa33cd601903b57329ab")
Run Code Online (Sandbox Code Playgroud)
是的,我也确定我已经定义了具有完全相同标识符的模型引用。
提前致谢!
我意识到不知何故我的StoryPart 和 Story 实例具有相同的 ID 。这就是为什么它什么也不返回。
编辑:
我通过确保并更正故事和故事部分的 ID 解决了该问题。我不会删除这个问题,因为可能有人面临同样的问题,所以只需检查您的 ObjectID 是否引用了正确的实例。