mongoose .find() method returns object with unwanted properties
Alternatively to Kevin B's answer, you can pass {lean: true}
as an option:
myModel.find({name: 'John'}, '-name', {lean: true}, function(err, results){
log(results[0])
}
In MongoDB, the documents are saved simply as objects. When Mongoose retrieves them, it casts them into Mongoose documents. In doing so it adds all those keys that are being included in your for
loop. This is what allows you to use all the document methods. If you won't be using any of these, lean
is a great option as it skips that entire process, increasing query speed. Potentially 3x as fast.
In this case .toObject would be enough to let your loop work the way you expect.
myModel.find({name: 'John'}, '-name', function(err, results){
log(results[0].toObject())
}
The extra properties you were getting originally are due to the fact that results
is a collection of model instances that come with additional properties and methods that aren't available on normal objects. These properties and methods are what are coming up in your loop. By using toObject
, you get a plain object without all of those additional properties and methods.