【问题标题】:findOneAndUpdate is not working in mongodbfindOneAndUpdate 在 mongodb 中不起作用
【发布时间】:2021-06-18 13:55:56
【问题描述】:

这是更新数据库的代码。

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",
}]

我试了好几次,结果都是一样的。
我该如何解决这个问题? 我认为有一些方法可以解决这个问题。

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    您正在尝试使用在架构中定义为 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)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      相关资源
      最近更新 更多