How to dynamically $set a subdocument field in mongodb? [duplicate]

牧云@^-^@ 提交于 2019-12-03 13:10:16

Figured this out.

Essentially, you need to construct a 'placeholder' object of the sub-document you're trying to update before running the query, like so:

var projectID = 'JKS78678923SDFD678';

var key = 'Three';
var value = 'Three';

var placeholder = {};
placeholder['options.' + key] = value;

Teams.findAndModify({
    query: {
        projectID:mongojs.ObjectId(projectID)
    },
    update: {
        $set : placeholder
    },
    upsert: true,
    multi: false,
    new: true
},
function(error, result, lastErrorObject){

    console.log(result);

});

This updates any fields that already exist, and creates the field/value pair if it didn't already exist.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!