子菜是MajorFood项目中的一个数组。我要添加子菜单(如果不存在),并更新子菜单(如果确实存在)。
我尝试使用addToSet更新方法。这对于普通元素正常工作,但对于数组则失败。
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();
});
当有价值的食物已经存在于子菜中时,更新工作正常。但是,当必须将元素添加到数组时,它会崩溃。
我收到以下错误:
MongoError: Cannot apply $addToSet to a non-array field.
Field named 'subdishes' has a non-array type Object
有一个方法可以在单个函数中执行此操作吗?
您将无法通过单个原子更新来执行此操作。您可以在更新函数中使用回调函数来检查是否有更新,如果没有更新,则将其推送到数组,因为该文档不存在:
MajorFood.update(
{
"_id": majorFoodId,
"subdishes.food" : rowVals[0]
},
{
"$set": {
"subdishes.$": {
//without $ you get the error The dotted field is not valid for storage
"energy.$.calories": s.getIntVal(rowVals[1]),
"energy.$.unit": rowVals[2]
}
}
},
function(err, numAffected, rawResponse) {
console.log(numAffected);
console.log(rawResponse);
if (!numAffected) {
/* Push to array if subdish doesn't exist hence there's no update */
MajorFood.update(
{ "_id": majorFoodId }
{
"$push": {
"subdishes": {
"food": rowVals[0],
"energy": {
"calories": s.getIntVal(rowVals[1]),
"unit": rowVals[2]
}
}
}
},
function(err, numAffected) {
if(err){
s.l("err update" );
callback(err);
return;
}
s.l("success");
callback();
}
);
}
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句