使用 mongoose 从 MongoDB 查询中获取不必要的信息

Getting unnecessary information back from MongoDB query using mongoose

我正在使用 mongoose 查询本地数据库并尝试过: (假设定义了 cardName

const card = await Card.findOne({ name: cardName }, 'name art description')

const card = await Card.findOne({ name: cardName }, { name: 1,art: 1,description: 1 })

const card = await Card.findOne({ name: cardName }).project('name art description')

const card = await Card.findOne({ name: cardName }, 'name art description').exec()

即使我得到了我指定的字段,我也得到了其他不必要的字段,例如

$__schema: [object Object]
collection: [object Object]
$collection: [object Object]
$__originalValidate: function(pathsToValidate, options, callback) { if (typeof pathsToValid . . .
$__save: function() { var _context = context || this; _this.wrap(name, fn, _context, Array.from(arguments), options); }
$__validate: function() { var _context = context || this; _this.wrap(name, fn, _context, Array.from(arguments), options); }
$__remove: function() { var _context = context || this; _this.wrap(name, fn, _context, Array.from(arguments), options); }
$__deleteOne: function() { process.nextTick(() => fn.apply(this, arguments)); }
$__init: function syncWrapper() { kareem.execPreSync(name, this, arguments); var toReturn = fn.apply(this, arguments); kareem.execPostSync(name, this, [toReturn]); return toReturn; }
$isMongooseModelPrototype: true
$__handleSave: function(options, callback) . . .

如何确保只获取我指定的字段而不是任何不必要的信息?

您可以在查询中使用 lean() 函数。来自文档:

Documents returned from queries with the lean option enabled are plain javascript objects, not Mongoose Documents. They have no save method, getters/setters, virtuals, or other Mongoose features.

const docs = await Model.find().lean();