【问题标题】:Getting unnecessary information back from MongoDB query using mongoose使用 mongoose 从 MongoDB 查询中获取不必要的信息
【发布时间】:2022-02-22 16:46:34
【问题描述】:

我正在使用猫鼬查询本地数据库并尝试过: (假设定义了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) . . .

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

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

    启用了精简选项的查询返回的文档是普通的 javascript 对象,而不是 Mongoose 文档。他们没有保存方法, getter/setter、virtuals 或其他 Mongoose 功能。

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

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2016-01-22
      相关资源
      最近更新 更多