我想使用findOneAndUpdate通过字段名称(riderUserId)更新文档
它的作用是代替riderUserId更新文档
updateProfile: function(req, res) {
var riderUserID = req.params.riderUserID;
profileModel.findOneAndUpdate(riderUserID, req.body,
{ overwrite: true, new: true }, (error, response) => {
if (error) {
res.json(error);
console.error(error);
return;
}
res.json(response);
});
},
这是我的模特
var profileSchema = new Schema({
name: { type: String },
surname: { type: String },
gender: { type: String },
email: { type: String },
riderUserId: { type: String },
mobileNumber: { type: Number },
birthYear: { type: Number },
nationality: { type: String },
idNumber: { type: String },
quickDescription: { type: String },
numberPlate: { type: String },
make: { type: Number },
model: { type: String },
memberType: { type: String },
accountHolderName: { type: String },
accountNumber: { type: Number },
nameOfBank: { type: String },
branchCode: { type: Number },
profilePicture: { type: String },
carPicture: { type: String },
music: { type: String },
conversations: { type: String },
pets: { type: String },
smoking: { type: String },
emailVerification: { type: Boolean },
phoneVerification: { type: Boolean },
idVerification: { type: Boolean },
});
这是两个文件,
{
"_id" : ObjectId("5bed37dc84fd420002791e0c"),
"email" : "shoba.hasini@gmail.com",
"riderUserId" : "ZH8irbzGt8WULt2lFSIU5J48Alz2",
"name" : "Shoba",
"surname" : "Hasini",
"gender" : "",
"mobileNumber" : null,
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("5bed37f484fd420002791e0d"),
"email" : "kartikajas@gmail.com",
"riderUserId" : "e1FUpfsDiwSVxcz50ZbhjWKfKGM2",
"name" : "Karthik",
"surname" : "Keyan",
"gender" : "",
"mobileNumber" : null,
"__v" : NumberInt(0)
}
更新文档后,通过findOneAndUpdate将两个文档变为相同
,{
"_id" : ObjectId("5bed37dc84fd420002791e0c"),
"name" : "Karthik",
"surname" : "Keyan",
"gender" : "male",
"email" : "kartikajas@gmail.com",
"riderUserId" : "e1FUpfsDiwSVxcz50ZbhjWKfKGM2",
"mobileNumber" : NumberInt(90087),
"idVerification" : false
}
{
"_id" : ObjectId("5bed37f484fd420002791e0d"),
"email" : "kartikajas@gmail.com",
"riderUserId" : "e1FUpfsDiwSVxcz50ZbhjWKfKGM2",
"name" : "Karthik",
"surname" : "Keyan",
"gender" : "",
"mobileNumber" : null,
"__v" : NumberInt(0)
}
为什么不使用riderId e1FUpfsDiwSVxcz50ZbhjWKfKGM2更新一个文档
答案 0 :(得分:0)
riderUserID
传递findOneAndUpdate
(是字符串)。但是猫鼬实际上将Object
作为搜索查询参数。您可能需要传递类似{_id:riderUserID}的对象。如果您的riderUserID是mongo对象ID。
从您的模式中,我可以看到您的riderUserID是一个字符串。将findOneAndUpdate(riderUserID, ...
替换为findOneAndUpdate({ riderUserID }, ...
,然后尝试。
更多信息
https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate