Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  180] [ 1]  / answers: 1 / hits: 19876  / 8 Years ago, mon, july 11, 2016, 12:00:00

I was trying to console.log(record._id) all of records on my mongodb collection using Mongoose. I kept getting undefined for each of the _id values.



I struggled until I bumped into this post. Then I used console.dir to find the location of the _id and used that in my console.log:



MySchemaModel.find({}).then(function(records) {

records.forEach(function(record) {

console.log(record._doc._id); // <-- I added ._doc
});

});


But, this looks down-right hacky. Is there a better way to do this?



NOTE: This isn't just something that affects console.log. I'm just keeping the question narrow.


More From » node.js

 Answers
149

If you want to customize/edit record then you should use .lean() function.The .lean() function will turn it into a normal JavaScript object. If you don't use .lean() function then each record is still a mongoose document and _id behaves differently in that context. So can use like



MySchemaModel.find({}).lean().exec(function(error, records) {
records.forEach(function(record) {
console.log(record._id);
});
});


N.B: when use .exec() then first parameter used for error and second one for success data.


[#61431] Friday, July 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maryann

Total Points: 600
Total Questions: 104
Total Answers: 97

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;