[英]findOneAndUpdate is not working in mongodb
這是更新數據庫的代碼。
let profileUrl = 'example'
UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true})
.then((updatedUser:UserModel) => {
console.log(updatedUser.profileUrl)
})
結果: undefined
正如您在結果中看到的, profileUrl
字段沒有更新。 所以我插入了overwrite
選項。
但它沒有用。 出現以下錯誤。
src/controllers/user.ts(267,106): error TS2345: Argument of type '{ new: true; overwrite: boolean; }' is not assignable to parameter of type 'ModelFindOneAndUpdateOptions'.
Object literal may only specify known properties, and 'overwrite' does not exist in type 'ModelFindOneAndUpdateOptions'.
UserSchema 與以下相同。
{
name:String,
thumbnailImg:String,
email:String,
phone:Number,
profileUrl:String
}
現在保存的數據如下。
[{
_id:ObjectId("5ffe07805cbab00019cdbbcd"),
name:"Jhon",
thumbnailImg:"thumbnail_image_url",
email:"jhon@gmail.com",
phone:"1212121212",
}]
我已經嘗試了幾次,但結果是一樣的。
我該如何解決這個問題? 我認為有一些方法可以解決這個問題。
您正在嘗試使用在架構中定義為 ObjectId 類型的_id
字段進行匹配。 因此,在您的查詢中,嘗試使用 ObjectId 類型進行搜索。
let ObjectId = require('mongoose').Types.ObjectId;
let profileUrl = 'example'
UserSchemaModel.findOneAndUpdate({_id: new ObjectId(userId)}, {
$set: {
profileUrl: profileUrl
}
}, {new:true}).then((updatedUser:UserModel) => {
console.log(updatedUser.profileUrl)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.