Reputation: 2313
When using the Model.findOne() method, I can choose to include a string that limits my return value to just those field, but when I try to do so with the findById method, it appears to not work out.
The example below is a contrived example. I'm using a real _id and it works when using the first example, but I just want to use the findById method because a tiny voice in the back of my mind is telling me that's faster (maybe).
Example:
let Joe = new PersonModel({
_id: ObjectId("12345")
name: 'Joe',
age: 30,
password: 'GreatPW'
}).save();
Now find Joe, and return only his name and age. This works!
PersonModel.findOne({_id: Joe._id}, 'name age')
.then(person => console.log(person))
Now do the same thing, but using findById(). This isn't working for me.
PersonModel.findById(Joe._id, 'name age')
.then(person => console.log(person))
Upvotes: 3
Views: 2936
Reputation: 960
I'm not sure but I think you need to write {}, on query and in the projection:
This:
PersonModel.findById(Joe._id, 'name age')
Should be this:
PersonModel.findById({idValueToFind}, {name:1, age:1, _id:0})
Upvotes: 3