【问题标题】:Inserting objects in MongoDB to field that can reference two different objects将 MongoDB 中的对象插入到可以引用两个不同对象的字段中
【发布时间】:2016-05-15 14:02:40
【问题描述】:

在我的项目中,我有一个如下所示的 Messages 模型:

var MessageSchema = new Schema({
fromId: {
    type: entityId,
    required: true
},
toId: {
    type: entityId,
    required: true
},
important: {
    type: Boolean, 
    required: false
},
lessonId: {
    type: Schema.Types.ObjectId, 
    ref: Models.Lesson,
    required: false
},
memberId: {
    type: Schema.Types.ObjectId, 
    ref: Models.Lesson,
    required: false
},
message: {
    type: String, 
    required: true
}});

只要用户和学校可以发送和接收消息,我就创建了一个复杂类型“entityId”,如下所示:

var entityId = {
id: {
    type: Schema.Types.ObjectId,
    required: true
},
entityName: {
    type: String,
    required: true,
    enum: entityTypeList.array
}};

我将其作为“类型”放在 MessageSchema 中的 fromId 和 toId 字段中(如上所示)。现在,当我尝试插入这样的实体时:

    sampleMessage1: {
    _id:"560e9504cac9a42f0e415bca",
    memberId: "5631f6883ad9bc561889f006",
    deleted:true,
    fromId:
        {
            entityName:"school",
            id:"55d1e957daea17d3e90a3c51"
        },
    toId:
        {
            entityName:"user",
            id:"569b89bb90d3ccd06d96644b"
        },
    important:false,
    message:"Sample message.",
    messageType:"notification",
    read:true,
    timestamp:"2015-07-31T16:11:32.714Z"
}

在 fromId 和 toId 的数据库中的“id”字段中使用“schema.create”,而不是 ObjectId,我得到了字符串。我知道我可以这样做:

id: new ObjectId(55d1e957daea17d3e90a3c51")

但我想知道是否有另一种解决方案,我不必更改我的示例消息,我可以在不使用任何 'ref:' 的情况下做一些我展示的事情吗?

【问题讨论】:

    标签: node.js mongodb mongoose schema


    【解决方案1】:

    您如何插入实体?如果你在做Message.insert(data),那么你就是在覆盖猫鼬。尝试先创建消息

    var message = new Message(data);
    message.save();
    

    【讨论】:

    • 我正在使用 schema.create。我试过 message.insert() 和 message.save() 但它也不起作用。如果字段可以引用来自两个不同模式的文档,我可以跳过“ref”属性吗?
    • 那我不确定。我知道您可以调用来填充和显式设置模型。 .populate({ path: 'fromId.id', model: fromId.entityName });也许这有帮助?
    猜你喜欢
    • 2020-07-16
    • 2021-07-01
    • 2019-01-17
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2013-06-23
    相关资源
    最近更新 更多