mongoose .find() method returns object with unwanted properties

后端 未结 2 769
余生分开走
余生分开走 2020-11-28 11:18

so, I\'ve been working with mongoose for some time and I found some really weird stuff going on. It would be great if someone could enlighten me.

The thing is, when

相关标签:
2条回答
  • 2020-11-28 12:12

    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.

    0 讨论(0)
  • 2020-11-28 12:14

    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.

    0 讨论(0)
提交回复
热议问题