使用upsert和findOneAndUpdate
设置为true的setDefaultsOnInsert
时,尝试在数据库中插入新用户时遇到麻烦。我想做的是设置以下架构的默认值:
var userSchema = new mongoose.Schema({
activated: {type: Boolean, required: true, default: false},
facebookId: {type: Number, required: true},
creationDate: {type: Date, required: true, default: Date.now},
location: {
type: {type: String},
coordinates: []
},
email: {type: String, required: true}
});
userSchema.index({location: '2dsphere'});
findOneAndUpdate
代码:model.user.user.findOneAndUpdate(
{facebookId: request.params.facebookId},
{
$setOnInsert: {
facebookId: request.params.facebookId,
email: request.payload.email,
location: {
type: 'Point',
coordinates: request.payload.location.coordinates
}
}
},
{upsert: true, new: true, setDefaultsOnInsert: true}, function (err, user) {
if (err) {
console.log(err);
return reply(boom.badRequest(authError));
}
return reply(user);
});
如您所见,我还存储了用户的纬度和经度,这就是问题的出处。调用
findOneAndUpdate
时出现此错误:{ [MongoError: exception: Cannot update 'location' and 'location.coordinates' at the same time]
name: 'MongoError',
message: 'exception: Cannot update \'location\' and \'location.coordinates\' at the same time',
errmsg: 'exception: Cannot update \'location\' and \'location.coordinates\' at the same time',
code: 16836,
ok: 0 }
当我删除2dsphere索引和所有与位置相关的代码时,它的确设置了creationDate。我做错了什么?
最佳答案
setDefaultsOnInsert
选项使用$setOnInsert
运算符执行其功能,这似乎与您自己使用$setOnInsert
设置location
产生冲突。
一种解决方法是删除setDefaultsOnInsert
选项,并将其全部放入您自己的$setOnInsert
运算符中:
model.user.user.findOneAndUpdate(
{facebookId: request.params.facebookId},
{
$setOnInsert: {
activated: false,
creationDate: Date.now(),
email: request.payload.email,
location: {
type: 'Point',
coordinates: request.payload.location.coordinates
}
}
},
{upsert: true, new: true},
function (err, user) {
if (err) {
console.log(err);
return reply(boom.badRequest(authError));
}
return reply(user);
});
关于node.js - Mongoose setDefaultsOnInsert和2dsphere索引不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31100908/