Question

I searched a lot on this topic, but I'm just totally lost. Here is my problem (I'm using node.js with mongojs):

I'd like to have this kind of documents:

{ 
    "_id" : ObjectId("50ce2f7f98fa09b20d000001"), 
    "beginTime" : 1355689855016, 
    "tags" : {
        "primary": [ 29, 12, 16], 
        "secondary": [6, 8, 9]
    },
    "user" : "50bdddc601de4681d666835f"
}

But if I try to push new tags for example under "primary" (note that this fields come from variables) like so

tags = {};
tags[request.body.relevance] = request.body.tag;
return db.activities.update({
  '_id': db.ObjectId(request.body.activity),
  'user': request.session.user.id
}, {
  $push: {
    tags: tags
  }
});

then I get

{ "_id" : ObjectId("50ce2f7f98fa09b20d000001"), "beginTime" : 1355689855016, "tags" : [ { "primary" : 29 }, { "primary" : "24" }, { "primary" : "1" } ], "user" : "50bdddc601de4681d666835f" }

I tried many other variations, including nesting the $push (witch tranformed it into a field o.o). Anyway, I always failed. Also at this point I'm really starving T_T

Please help me. Thanks.

Was it helpful?

Solution

The value of a $push operator needs to be the array field you want pushed to, not the parent.

Try this instead:

...
return db.activities.update({
  '_id': db.ObjectId(request.body.activity),
  'user': request.session.user.id
}, {
  $push: {
    'tags.primary': tags.primary,
    'tags.secondary': tags.secondary
  }
});

UPDATE

To do this dynamically you need to do something like this:

...
var push = {};
push['tags.' + request.body.relevance] = request.body.tag;
return db.activities.update({
  '_id': db.ObjectId(request.body.activity),
  'user': request.session.user.id
}, {
  $push: push
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top