【问题标题】:How to add value to array element withing collection using mongoose?如何使用猫鼬为数组元素添加值?
【发布时间】:2019-10-15 18:18:15
【问题描述】:

我已经编写了以下 mongoose 函数来在 mongodb 中创建新文档

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
       //,
       //notes.message: body.message   
    }));
    return sEntry.save();
}

这里sData 架构包含notes 数组架构。

我无法使用notes.message: body.messagenotes [] 内的message 添加价值

我的架构定义如下:

var nSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    message: String
});

var sSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    dataId: { type:String, unique: true },
    notes: [nSchema]
}

我还想提一下,对于每个 dataId,可以有多个 notes [] 条目。但是,SData 对于每个 dataId 只能有唯一的行条目。

我希望 notes 成为 SData 集合中的一个数组。如何在不创建单独的notes 集合的情况下实现它?我应该如何修改createdata 以适应所有给定的要求。

【问题讨论】:

    标签: angularjs mongoose angularjs-directive mongoose-schema mongoose-populate


    【解决方案1】:

    其他集合映射使用references,获取时使用populate

    架构设计

    var sSchema = new Schema({
        _id: {type:ObjectId, auto: true },
        dataId: { type:String, unique: true },
        notes: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'nSchema',
        }]
    }
    

    添加数据

    createdata: (body) => {
        let sEntry = new SData({
            dataId: body.DataId,
            notes: [nSchemaIds]
        });
        return sEntry.save();
    }
    

    【讨论】:

    • 我应该创建单独的create function 来添加注释吗?另外,notes 会是一个单独的集合吗?
    • Notes 是一个单独的集合,我认为这就是您想要的。插入注释后,您将其引用添加到另一个集合
    • 我希望笔记成为SData 集合中的一个数组。如何在不创建单独的notes 集合的情况下实现?
    猜你喜欢
    • 2018-08-11
    • 2022-01-25
    • 2020-12-31
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2022-11-10
    相关资源
    最近更新 更多