【发布时间】:2018-07-30 17:51:33
【问题描述】:
我查找了其他问题,包括 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 是 Story 通过 storyController.js 传递的
这就是我所说的填充:
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")
是的,我也确定我已经定义了具有完全相同标识符的模型引用。
提前致谢!
【问题讨论】:
-
如果去掉
.populate('candidateParts')部分,console.log(populatedStory)中记录的结果是否在candidateParts数组中有任何内容? -
@chridam 是的,部分的 id 像这样返回
[ 5a8c2df95eb65602b02e0687 ] -
如果您在 mongo shell 中使用该 ID 查询
storyparts集合,例如db.storyparts.findOne({ _id: ObjectId("5a8c2df95eb65602b02e0687") }),您会得到任何文档吗? -
@chridam 我发现 StoryPart 和 Story 实例的 ID 相同。我在保存新零件时应该有问题。
标签: javascript node.js mongodb mongoose populate