Mongoose find() return a weird property

Viewed 156

I just learnt mongoose in node.js, but when I use the collection.find(), it return a weird properties like below:

model {
    '$__': InternalCache {
      strictMode: true,
      selected: {},
      shardval: undefined,
      saveError: undefined,
      validationError: undefined,
      adhocPaths: undefined,
      removing: undefined,
      inserting: undefined,
      version: undefined,
      getters: {},
      _id: 61d95a65fb65d62fb20ecb88,
      populate: undefined,
      populated: undefined,
      wasPopulated: false,
      scope: undefined,
      activePaths: [StateMachine],
      pathsToScopes: {},
      ownerDocument: undefined,
      fullPath: undefined,
      emitter: [EventEmitter],
      '$options': true
    },
    isNew: false,
    errors: undefined,
    _doc: {
      tags: [Array],
      date: 2022-01-08T09:33:25.205Z,
      _id: 61d95a65fb65d62fb20ecb88,
      name: 'Angular Course',
      author: 'meow',
      isPublished: true,
      __v: 0
    },
    '$init': true
  }

If I run it in terminal using mongodb instead of mongoose, I got the correct answer like that:

> db.courses.find()
{ "_id" : ObjectId("61d9592205df8e2f7230932f"), "tags" : [ "node", "backend" ], "date" : ISODate("2022-01-08T09:28:02.467Z"), "name" : "Node.js Course", "author" : "meow", "isPublished" : true, "__v" : 0 }
{ "_id" : ObjectId("61d95a65fb65d62fb20ecb88"), "tags" : [ "Angular", "frontend" ], "date" : ISODate("2022-01-08T09:33:25.205Z"), "name" : "Angular Course", "author" : "meow", "isPublished" : true, "__v" : 0 }
1 Answers

Use lean()

Normally, in mongoose, find() returns mongoose document not plain javascript object. Use lean() to returns a plain javascript object.

async function getCourses() {
    // Documents returned from queries with the lean option enabled are plain javascript objects, not Mongoose Documents. 
    // read more: https://mongoosejs.com/docs/api.html#query_Query-lean
    const courses = await Course.find().lean(); 
    console.log(courses);

};
Related