Gabriel Kunkel Gabriel Kunkel - 4 months ago 35
Node.js Question

get _id with mongoose

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.

Answer

If you want to find _id of each record then you can use like this.

MySchemaModel.find({}).exec(function(error,records) {
  //forEach(records, function(record)// can try this line instead of bellow line
  records.forEach(function(record) {
    console.log(record._id);
  });
});

But if you want to customize/edit record then you should use .lean() function.

MySchemaModel.find({}).lean().exec(function(error, records) {
  records.forEach(function(record) {
    record._doc = record // as you want
    console.log(record._doc._id);
  });
});