当使用findOneAndUpdate
将upsert和setDefaultsOnInsert
设置为true时,我尝试在数据库中插入新用户时遇到问题。我所试图做的是设置以下模式的默认值:Mongoose setDefaultsOnInsert和2dsphere索引不起作用
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。我做错了什么?
我正在考虑这样做,但这是否意味着猫鼬中存在一个错误? – Jdruwe
@Jdruwe是的,我认为这个问题是Mongoose中的一个错误。在这种情况下,它不应该试图将'location.coordinates'设置为空数组。 – JohnnyHK
好的,我在github回购上创建了一个问题,谢谢你的时间! – Jdruwe