【问题标题】:findOneReplace replacment issuefindOneandReplace 替换问题
【发布时间】:2022-01-29 21:02:18
【问题描述】:

我想在我的数据库中找到一个文档并将其替换为具有新名称和新密钥的文档。

这是我的架构

const Schema = mongoose.Schema;

const vampireSchema = new Schema({
  name: { type: String, required: true },
  title: String,
  hair_color: {type: String, default: "blonde" },
  eye_color: String,
  dob: Date,
  loves: [String],
  location: String,
  gender: String,
  victims: {type: Number, min: 0}

});

const Vampire = mongoose.model("Vampire", vampireSchema);

module.exports = Vampire;

这是我的可执行代码

Vampire.findOneAndReplace( { name: "Claudia" }, { name: "Eve", portrayed_by: "Tilda Swinton" }, (err, vamp) => {
  if(err){
    console.log(err)
  }
  else{
    console.log(vamp)
  }
  db.close()
})

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我可以看到两个问题。

    首先,您应该在 findOneAndReplace 调用中将 null 作为第三个参数传递。这会将选项设置为 null 并且应该让您的代码运行。在我看来,这是猫鼬的一种奇怪行为。

    Vampire.findOneAndReplace( 
            { name: "Claudia" }, 
            { name: "Eve", portrayed_by: "Tilda Swinton" }, 
            null, 
            (err, vamp) => 
    {
      if(err){
        console.log(err)
      }
      else{
        console.log(vamp)
      }
      db.close()
    })
    

    其次,我建议将 describeed_by 添加到架构中,否则,该字段将不会出现在新创建的文档中。因此,我会以这种方式调整您的架构:

    const vampireSchema = new Schema({
      name: { type: String, required: true },
      title: String,
      hair_color: {type: String, default: "blonde" },
      eye_color: String,
      dob: Date,
      loves: [String],
      location: String,
      gender: String,
      victims: {type: Number, min: 0},
      portrayed_by: String
    });
    

    【讨论】:

    • 哦哈哈,谢谢我真的很感激。我没有将 portayed_by 添加到架构中,因为从我阅读的内容来看,MongoDB 允许传入任何内容,但我想我需要在使用 mongoose 时进行澄清。
    • @Saifalushi,是的,Mongoose 的架构更严格一些,因此这是一个常见的陷阱。很高兴,我能帮上忙!
    猜你喜欢
    • 2014-06-12
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多