【问题标题】:update collection based upon other collection field根据其他集合字段更新集合
【发布时间】:2021-08-27 03:49:47
【问题描述】:

我有 2 个架构,这是父集合架构:

const TimesheetSchema = Schema({
    managersComment: {
        type: String,
    },
    weekNum: {
        type: Number,
    },
    year: {
        type: Number,
    },
    user: { type: Schema.Types.ObjectId, ref: userModel },
    status: {
        type: String,
        enum: ["Saved", "Submitted", "Approved", "Rejected"],
    },
    data: [{ type: Schema.Types.ObjectId, ref: TimesheetIndividualData }]
});

这是子集合架构

const TimesheetDataSchema = new Schema(
    {
        workingDate: {
            type: Date,
        },
        dayVal: {
            type: Number,
        },
        user: { type: Schema.Types.ObjectId, ref: userModel },
        parentId: { type: String },
        status: { type: String }
    },
    { timestamps: true }
);

我想根据parentId更新TimesheetDataSchema(child collection)中的所有status字段,这里parentId基本上就是TimesheetSchema (parent collection)的_id。

不知道如何通过 mongoose/mongo 中的查询来做到这一点,所以我试图通过 express 中的代码来做到这一点。

请帮忙。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    db.timeSheetData.updateMany({"parent_id": ObjectId(_id)}) 怎么样?

    (编辑)

    • 从TimeSheetSchema 集合中获取数据。
    • 遍历它并为每个data 获取_id。
    • db.timeSheetsData.updateMany({"parent_id": _id}, {"$set": {"status": data.status}

    【讨论】:

    • 嗨,我想从TimesheetSchema 获取状态字段值并根据条件TimesheetSchema ._id === TimesheetDataSchema .parentId 更新TimesheetDataSchema 集合中的值
    猜你喜欢
    • 2021-07-25
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多