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

感情迁移 提交于 2019-12-21 04:14:38

问题


I've run into a situation where I need to dynamically update the value of a field in a subdocument. The field may or may not already exist. If it doesn't exist, I'd like mongo to create it.

Here's an example document that would be found in my Teams collection, which is used to store members of any given team:

{
  _id : ObjectId('JKS78678923SDFD678'),
  name : "Bob Lawblaw",
  status : "admin",
  options : {
    one : "One",
    two : "Two"
  }
}

And here's the query I'm using (I'm using mongojs as my mongo client) to try and update (or create) a value in the options subdocument:

var projectID = 'JKS78678923SDFD678';
var key = 'Three';
var value = 'Three';

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

    console.log(result);

});

But I can't get it to 'upsert' the value.

I also found this similar question, but that method didn't work either: Nodejs Mongo insert into subdocument - dynamic fieldname

Thanks in advance for any help.


回答1:


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.



来源:https://stackoverflow.com/questions/24986026/how-to-dynamically-set-a-subdocument-field-in-mongodb

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