I'm running the following using nodejs native mongodb client:
db.collection("users").findAndModify(
{ _id:ObjectID.createFromHexString(id), "profiles._id":pid}, {},
{ '$addToSet' : {'profiles.$.categories': category}}, {new:true},
function(err, user){
if(err){
res.json(err);
}
}
);
I have a category I want to add to the categories set, the problem is that after the run I see a new category in the set but an items array that was part of the category is set to null and was not saved. Meaning a category looks like that:
{
name:'n1',
items:['it1', it2']
}
A full document looks like that:
{
_id: ...
profiles: [
{
_id: ...
categories: [
{
name:'c1',
items:['it1', it2']
},
{
name:'c2',
items:['it3', it4']
}
]
}
]
}
This works as expected for me in the Mongo shell:
> var id = ObjectId(), pid = ObjectId();
> db.users.insert({
... _id: id,
... profiles: [
... {
... _id: pid,
... categories: [
... {
... name: 'c1',
... items: ['it1', 'it2']
... },
... {
... name: 'c2',
... items: ['it3', 'it4']
... }
... ]
...
... }
... ]
... });
>
> var category = {
... name:'n1',
... items:['it1', 'it2']
... };
>
>
> db.users.findAndModify({
... query: { _id: id, "profiles._id": pid},
... update: {
... '$addToSet' : {'profiles.$.categories': category}
... },
... new:true
... });
{
"_id" : ObjectId("51bfc532c0a62b206198663e"),
"profiles" : [
{
"_id" : ObjectId("51bfc532c0a62b206198663f"),
"categories" : [
{
"name" : "c1",
"items" : [
"it1",
"it2"
]
},
{
"name" : "c2",
"items" : [
"it3",
"it4"
]
},
{
"name" : "n1",
"items" : [
"it1",
"it2"
]
}
]
}
]
}