我对使用" upsert"的方式有疑问。查询猫鼬。由于特定模型的某些原因,即使upsert为true,它也不会插入新模型。它也没有发出错误告诉我为什么它没有更新。它只返回numAffected = 0,这是我当前的方法
query = {gatewayId:req.body.gatewayId};
body = {$push:{xbees:{$each: req.body.xbees}},
"$setOnInsert":{address:req.body.address}};
options = [{upsert:true},{runValidators:true}]
GatewayData.update(query,body,options,function(err,numAffected,rawResposne){
if (err) return next(err);
if(numAffected == 0){
console.log("ohno!");
}
});;
以下是参考模型的副本
var xbeeMapping = new mongoose.Schema({
...
});
var GatewayData = new mongoose.Schema({
address: {type: String, uppercase:true, required:true},
gatewayId: {type: String, match : validators.gateway_matcher, required: true},
timestamp: {type: Date, default: Date.now},
panID: {type: String, uppercase:true},
radThreshold: {type: Number, default:30},
roomThreshold: {type: Number, default:22.22},
radCritical: {type: Number, default:15},
roomCritical: {type: Number, default:19.5},
xbees:[xbeeMapping]
});
GatewayData.index({gatewayId:1});
module.exports = mongoose.model('GatewayData', GatewayData);
请注意,只有在插入时才能正常更新。我也很抱歉,如果这太浪费了,请告诉我是否应该从问题中删除我的架构。
答案 0 :(得分:0)
Kevin B在评论中提到打开调试。 我做了,发现了以下内容:
Mongoose: gatewaydatas.update({
gatewayId: '00000000-00000000-00409DFF-FFFFFFFD' })
{ '$push':
{ xbees:
{ '$each':
[ { serialNumber: '40AC1233',
roomNumber: 'LR', xbeeAddress:
'NODE_[40:AC:12:33]!',
_id: ObjectId("55563d50f9c72ca75c15612c") } ] } },
'$setOnInsert': { address: 'Stephens' } } {} –
选项未正确阅读!!
选项的正确格式是
options = {upsert:true, runValidators:true}
不
options = [{upsert:true},{runValidators:true}]