2

I have a mongo collection that looks like this:

{

"_id" : "FfnHWrZuvzBqAk7M5",

"0" : {
    "ids" : [ 
        "3", 
        "1"
    ]
},

"1" : {
    "who" : "3",
    "txt" : "aaa",
    "time" : "1100"
},

"2" : {
    "who" : "1",
    "txt" : "bbb",
    "time" : "1101"
},

"3" : {
    "who" : "1",
    "txt" : "ccc",
    "time" : "1101"
}

The above is a single document that contains and '_id', the 'ids', then other objects from 1 to eternity with the same set of fields.

I'm trying to update a document by adding the next object (in this example it'd be 4th) like this:

var foo = (some data here);

MNChats.update(
  { _id: Session.get('activeConversationID')},
  { $set: {foo: {who: '3', txt: 'whatever', time: '2100'} } }
);

It works fine, but inserts 'foo' instead of a number stored in the variable.

How can I use a variable in this case?

Or is there any other way I could insert this object automatically under the next number?

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
KG32
  • 150
  • 10
  • possible duplicate of [How to set mongo field from variable](http://stackoverflow.com/questions/17362401/how-to-set-mongo-field-from-variable) – Dan Dascalescu Feb 22 '15 at 01:05

1 Answers1

2

You need to create an object where the value of foo becomes the key, and pass that to the $set operator.

var whatToSet = {};
var foo = 4;  // or your number you want to store
whatToSet[foo] = {who: '3', txt: 'whatever', time: '2100'};
MNChats.update(
  {_id: Session.get('activeConversationID')},
  { $set: whatToSet }
);

You may also want to revise this data structure to be an array, so you'll be able to use the $push operator.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • 1
    I wish I could, 15 points of reputation are required to upvote. But I'll remember to do that as soon as I get more points, especially since I spent hours trying to figure it out. Thanks again – KG32 Feb 22 '15 at 01:28