【问题标题】:Mongoose return data inside _doc objectMongoose 在 _doc 对象内返回数据
【发布时间】:2021-06-29 17:18:32
【问题描述】:

mongoose find 查询执行时,响应数据为多个对象,真实数据在_doc 属性或字段中,仅在某些场景中出现。我可以通过获取 Obj._doc.something 来处理数据,但我无法编辑数据并保存(猫鼬模型函数)。请帮我解决这个问题。

注意:架构的字段是动态添加的。

PatientOrderMigration.find({ mrn: orderitem.mrn, visituid: orderitem.visituid },
function (err, orderDoc) 
{ 
//log data correctly.
console.log(orderDoc);
// undefined
console.log(orderDoc._id);
// correct data
console.log(orderDoc._doc._id);
}

【问题讨论】:

  • 请添加您的代码以帮助人们理解问题并让他们写出更好的答案。
  • _doc 是您不应该访问的私有字段。不管怎样,orderDoc 是一个带有find 的数组,你可能想要findOne 这里。

标签: node.js mongodb mongoose


【解决方案1】:

我知道这是旧的,但我有类似的问题。要解决此问题,请使用 .lean()。

精益选项告诉 Mongoose 跳过对结果文档进行水合。这使得查询更快,内存占用更少,但结果文档是普通的旧 JavaScript 对象 (POJO),而不是 Mongoose 文档。

所以您的查询将是:

PatientOrderMigration.find({ mrn: orderitem.mrn, visituid: orderitem.visituid }).lean()

【讨论】:

    【解决方案2】:

    好吧,Model.find() 将为您提供在 DB 上找到的对象数组,如果您想直接访问您的对象,您可以使用 Model.findOne()

    OR => 快速修复:

    PatientOrderMigration.find({ mrn: orderitem.mrn, visituid: orderitem.visituid },function (err, orderDoc) {
    
        orderDoc = orderDoc[0];//Here is the Fix, you can comment this if you use findOne
    
        orderDoc.mrn = "New Value you want to update";
    
        orderDoc.save(function(err, result){
               console.log('err',err)
       })
    }}
    

    【讨论】:

      【解决方案3】:

      起源问题是find 方法返回一个数组,这是由接受的答案指出的。但标题“Mongoose 在 _doc 对象内返回数据”与另一个常见错误有关。所以我想在这里继续我的研究。


      当您使用 Mongoose API 查询数据(find、findOne、findById ..)时,Mongoose 会在响应中为您提供一个 Mongoose Document 类的实例,它与您的 不同Javascript 对象。

      您有一些选项来获取您的 Javascript 对象,如文档中所述:

      • 使用lean()方法:查看文档here
      • 使用 toObject() 方法:查看文档here

      我创建了一个测试项目来演示这些方法,请随意测试:

      const mongoose = require('mongoose');
      
      // connect to database
      mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });
      
      // define the schema 
      const kittySchema = new mongoose.Schema({
          name: String
      
          // this flag indicate that the shema we defined is not fixed, 
          // document in database can have some fields that are not defined in the schema
          // which is very likely
      }, { strict: false });
      
      // compile schema to model
      const Kitten = mongoose.model('Kitten', kittySchema);
      
      test();
      async function test() {
      
      
          // test data
          const dataObject = { name: "Kitty 1", color: "red" };
          const firstKitty = new Kitten(dataObject); // attribute color is not defined in the schema
      
          // save in database
          firstKitty.save();
      
          // find the kitty from database
          // mongoose return a document object, which is different from our data object
          const firstKittyDocument = await Kitten.findOne({ name: "Kitty 1" });
          console.log("Mongoose document. _id :", firstKittyDocument._id); // _id of document
          console.log("Mongoose document. name :", firstKittyDocument.name); // "Kitty 1"
          console.log("Mongoose document. color :", firstKittyDocument.color); // undefined
          // --> the document contains _id and other fields that we defined in the schema
      
          // we can call the method .toObject to get the plain object
          console.log("Using .toObject() method. _id :", firstKittyDocument.toObject()._id); // _id of document
          console.log("Using .toObject() method. name :", firstKittyDocument.toObject().name); // "Kitty 1"
          console.log("Using .toObject() method. color :", firstKittyDocument.toObject().color); // "red"
          // --> Using .toObject() method, we get all the fields we have in the dataObject
      
          // or we can use lean method to get the plain old javascript object
          const firstKittyPOJO = await Kitten.findOne({ name: "Kitty 1" }).lean();
          console.log("Using .lean() method. _id :", firstKittyPOJO._id);  // _id of document
          console.log("Using .lean() method. name :", firstKittyPOJO.name); // "Kitty 1"
          console.log("Using .lean() method. color :", firstKittyPOJO.color); //"red"
          // --> Using .lean() method, we get all the fields we have in the dataObject
      }
      

      【讨论】:

        猜你喜欢
        • 2018-12-16
        • 2013-09-20
        • 2017-11-17
        • 2020-09-14
        • 2017-10-26
        • 2014-07-09
        • 2020-11-11
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多