【问题标题】:Mongoose.populate() returns empty array instead of dataMongoose.populate() 返回空数组而不是数据
【发布时间】: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


【解决方案1】:

我意识到我有 相同的 ID 用于 StoryPart 和 Story 实例。这就是为什么它什么也不返回。

编辑:

我已通过确保和更正故事和故事部分的 ID 来解决问题。我不会删除这个问题,因为可能有人面临同样的问题, 所以只需检查您的 ObjectID 是否引用了正确的实例

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    相关资源
    最近更新 更多