當使用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