How to dynamically set $ subdocument field in mongodb?

I came across a situation where I need to dynamically update the value of a field in a sub-folder. A field may or may not exist. If this does not exist, I would like mongo to create it.

Here is an example of a document that will be found in my collection Teams, which is used to store members of a team:

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

And here is the query that I use (I use mongojs as my mongo client) to try and update (or create) the value in the subdocument options:

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 not get it to "update" the value.

I also found this similar question, but this method also did not work: Nodejs Mongo paste into subdocument - dynamic field name

.

+4
1

.

, "placeholder" , , , :

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);

});

/, .

+4

All Articles