Subdishes is a array in the item MajorFood. I want to add subdishes if they don't exist and update the subdishes if they do exist.
I tried the update method with addToSet. This works fine for a normal element but fails for an array.
MajorFood.update({'_id' : majorFoodId, 'subdishes.food' : rowVals[0]},
{$addToSet : {subdishes : {
food : rowVals[0],
energy : {
calories : s.getIntVal(rowVals[1]),
unit : rowVals[2]
}
}}}, {upsert : true}, function(err, doc){
if(err){
s.l("err update" );
callback(err);
return;
}
s.l("success");
callback();
});
The update works fine when the value food already exists in subdishes. But it crashes when an element has to be added to the array.
I am getting the following error:
MongoError: Cannot apply $addToSet to a non-array field.
Field named 'subdishes' has a non-array type Object
Is there a method to do this in a single function?
subdishesis not an array as you expect.subdishes: {$type: 'object'}will resolve to true in both cases, whensubdishesis an object and when it is an array of objects: docs.mongodb.com/manual/reference/operator/query/type/#arrays