Mongodb文档保存不适用于嵌套模式

时间:2018-10-22 17:26:39

标签: node.js mongodb express mongoose

我有一个具有不同架构的简单Nodejs / Mongodb项目,但是当我尝试更新嵌套文档中的属性时,mongodb不会更新数据库。

架构组:

const GroupSchema = new Schema({
    settings: {
        type: Schema.ObjectId,
        ref: 'groupSettings',
        required: true,
    }
});

const Group = mongoose.model('groups', GroupSchema);

架构组设置:

const GroupSettingSchema = new Schema({
currency: {
    type: String,
    required: true,
    default:'cad'
},
});

const GroupSetting = mongoose.model('groupSettings', GroupSettingSchema);

Express.js路由功能:

let group = await Group.findById(id).populate('settings').exec()
    .catch(err => {
        return sendError(res, DatabaseFindError, err)
    })

if (!group) {
    return sendError(res, NotFoundError)
}

//HERE group.settings == old value

//change property send by the body
Object.keys(req.body.settings).forEach(key => {
    let value = req.body.settings[key];
    if (isDefined(group.settings[key])) {
        //only modify if keys exist
        //THIS WORK
        group.settings.set(key, value);

    }
});

 //HERE group.settings == new value

 await group.save()//DB IS NEVER UPDATED
    .catch(err => {
        return sendError(res, DatabaseSaveError, err)
    })

return sendSuccess(res, {
    settings: group.settings// THIS RETURN NEW VALUE
})

猫鼬数据库调试模式真实日志:

Mongoose: users.findOne({ _id: ObjectId("5bc4e6e2f37badaaeaa1ef9d") }, { projection: {} })
Mongoose: groups.findOne({ _id: ObjectId("5bca88c9ec9c9583c7bf0c86") }, { projection: {} })
Mongoose: groupsettings.find({ _id: { '$in': [ ObjectId("5bca88c8ec9c9583c7bf0c82") ] } }, { projection: {} })

::ffff:127.0.0.1 - - [22/Oct/2018:17:18:18 +0000] "POST /api/groups/5bca88c9ec9c9583c7bf0c86/modify/settings HTTP/1.1" 200 63 "http://localhost:3000/admin/groups/5bca88c9ec9c9583c7bf0c86/settings" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"

所以猫鼬甚至不执行.save吗?

为什么?

谢谢,如果您需要更多详细信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

对于有此问题的任何人,您都需要在保存组后保存设置本身,这样:

await group.settings.save()//DB IS NOW UPDATED
    .catch(err => {
        return sendError(res, DatabaseSaveError, err)
    })

之后:

await group.save()//DB IS NEVER UPDATED
    .catch(err => {
        return sendError(res, DatabaseSaveError, err)
    })

谢谢