gpt4 book ai didi

node.js - Mongoose setDefaultsOnInsert 和 2dsphere 索引不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:54 25 4
gpt4 key购买 nike

使用 findOneAndUpdate 并将 upsert 和 setDefaultsOnInsert 设置为 true 时,尝试在数据库中插入新用户时遇到问题。我想做的是设置以下架构的默认值:

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 索引和所有位置相关代码时,它确实设置了我的创建日期。我做错了什么吗?

最佳答案

setDefaultsOnInsert 选项使用 $setOnInsert 运算符来执行其功能,这看起来与您自己使用 $setOnInsert 相冲突设置位置

解决方法是删除 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com