Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 288
AJB Avatar asked Jul 27 '14 21:07

AJB


Video Answer


1 Answers

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.

like image 100
AJB Avatar answered Oct 16 '22 00:10

AJB