业务架构:
var BusinessSchema = new Schema({
owners: {type: Array},
templates:[{
_id : ObjectId,
title : String,
path : String,
custom_navigation : Boolean
}]
});
业务集合看起来像这样:
{"owners" : [
ObjectId("522fa2d61685d3f4ce000002")
],
"templates" : [
{
"_id" : ObjectId("524c3bacc7ba62c549000004"),
"custom_navigation" : true
},
{
"_id" : ObjectId("524c3bacc7ba62c549000005")
},
{
"_id" : ObjectId("524c3bacc7ba62c549000006")
}
]}
用于更新存储在templates数组中的特定模板的函数:
var Business = require('../models/business.js');
Business.update({'owners' : req.user._id, "templates._id" : req.body._id}, {
$set : {"templates.$.custom_navigation" : req.body.custom_navigation}
},
function(err, numUpdated){
console.log(numUpdated);
if(numUpdated > 0){
res.json(200, req.body);
}else{
res.json(404);
}
});
当我输出 update
函数的搜索参数时,我看到:
{ owners: 522fa2d61685d3f4ce000002,
'templates._id': '524c3bacc7ba62c549000004' }
注意,Mongoose似乎将req.user._id识别为ObjectId,但req.body._id作为字符串传递 . 我尝试将其转换为ObjectId但没有结果 . 无论template._id设置为什么,update语句总是更新templates数组中的第一项 .
1 回答
你需要通过Object id搜索,而不是通过req.body._id搜索(我猜它是一个整数)