Home > Blockchain >  Getting unnecessary information back from MongoDB query using mongoose
Getting unnecessary information back from MongoDB query using mongoose

Time:02-22

I am using mongoose to query a local database and have tried: (Assume cardName is defined)

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()

Even though I get the fields I specify I also get other unnecessary fields such as

$__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) . . .

How do I ensure that I only get the fields I specify and NOT any of the unnecessary information?

CodePudding user response:

You can use the lean() function on your query. From the docs:

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();
  • Related