起源问题是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
}