【问题标题】:How to popoulate recursive schema references Mongodb, Mongoose, Express?如何填充递归模式引用 Mongodb、Mongoose、Express?
【发布时间】:2016-10-18 06:33:34
【问题描述】:

在 mongodb 中使用 mongoose 和 Express

所以现在我有一个框的架构,一个框可以包含对象,也可以包含其他框:

我的盒子架构如下所示:

var box =  new Schema({
    boxId: ObjectId,
    boxContents: [{
        contentType: {
            type: String,
            enum: ["box", "object"]
        },
        typeId: {
            subBox: {
                type: Schema.Types.ObjectId,
                ref: 'box'
            },
            subObject: {
                type: Schema.Types.ObjectId,
                ref: 'object'
            }
        }
    }]
});

我确保将我的“参考”标记为相应的型号名称,所以我认为这不是问题所在。我像这样创建一个新文档:

var box1 = new Box({
    contents: [{
        contentType: 'object',
        typeId: {
            subObject: object1._id
        }
    }]
});

当我使用时:

Control.find({}).populate('contents.typeId')
.exec(function(error, posts) {
    console.log(JSON.stringify(posts, null, "\t"));
});

它不会填充 subBox 和 subObject 字段 :( 如果我尝试访问 subBox 或 subObject 字段,它会给我未定义。 我做错了什么?

【问题讨论】:

  • 数据库中是否存在subObject_id
  • 是的,我添加了 subObject 和 subBox,当我查看数据库时,都显示了
  • 您能否使用数据库中的示例对象更新您的问题?

标签: node.js mongodb mongoose mongoose-populate mongoose-schema


【解决方案1】:

首先,你需要得到一个集合的模型:

var BoxModel = mongoose.connect(dbURI).model("box", box);

boxContents 在模式中,但在对象中是内容,应该修改。 要创建要保存的对象,您需要以这种方式使用模型,然后您可以通过这种方式获取填充的数据:

var box1 = new BoxModel({
    boxContents: [{
        contentType: 'object',
        typeId: {
            subObject: object1._id
        }
    }]
});


BoxModel.find({}).populate('boxContents.typeId');
OR
BoxModel.find({}).populate({path:'boxContents.typeId'});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 2019-06-25
    • 2017-05-04
    • 1970-01-01
    • 2020-10-14
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多