【问题标题】:how to get a field that is not part in the Schema in Mongoose如何获取不属于猫鼬模式的字段
【发布时间】:2020-08-25 12:05:59
【问题描述】:

在我的数据库中,有时我需要为要添加的文档再添加一个字段,我使用了{strict: false} 在我的架构中是这样的: const mySchema = mongoose.Schema({name: String, description: String}, { strict: false }); 并且添加时效果很好,但是当我想要获取具有此新值的记录时出现问题,我无法使用此字段并显示未定义,这是一个示例:

假设我正在制作这样的唱片:

myModul.insertMany([{name: 'test', description: 'test description', auto: true}], (error, docs) {});

因为{ strict: false } 现在它已经被添加了

现在,当我想获得该记录时,我会使用它:

myModul.findOne({name: "test"}, (err, found)=>{
  console.log(found);
  console.log(found.auto);
});

第一个 console.log 显示记录中的字段,但是当我想专门记录或使用该字段时,它显示未定义

【问题讨论】:

    标签: javascript node.js mongodb web mongoose


    【解决方案1】:

    从猫鼬的角度来看,如果您想获得一个不在架构中的字段,您必须执行instance.setinstance.get。这是一个例子:

    let func = async () => {
      let instance = new Model()
      instance.fieldOne = 'abc'
      instance.set('fieldTwo', 'def')
      await instance.save()
    
      let instance2 = await Model.findOne({_id: instance._id})
    
      console.log(instance2.fieldOne)
      console.log(instance2.get('fieldTwo'))
      // Has `fieldTwo`
      console.log(instance2.toObject())
    }
    

    您可以结帐更多here

    所以你的情况是:

    myModul.findOne({name: "test"}, (err, found)=>{
      console.log(found);
      console.log(found.get('auto'));
    });
    

    【讨论】:

    • 你刚刚给了我我想要的信息,非常感谢
    猜你喜欢
    • 2021-08-21
    • 2021-06-20
    • 2012-12-27
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2021-07-08
    • 2015-04-11
    • 2021-09-12
    相关资源
    最近更新 更多