Gabriel Kunkel Gabriel Kunkel - 1 year ago 239
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

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 Source

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) {

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download