Mongoose/MongoDB result fields appear undefined in Javascript

前端 未结 10 2290
囚心锁ツ
囚心锁ツ 2020-11-27 20:13

Is there something that I\'m missing that would allow item to log as an object with a parameter, but when I try to access that parameter, it\'s undefined?

What I\'ve

10条回答
  •  不知归路
    2020-11-27 20:30

    A better way to tackle an issue like this is using doc.toObject() like this

    doc.toObject({ getters: true })
    

    other options include:

    • getters: apply all getters (path and virtual getters)
    • virtuals: apply virtual getters (can override getters option)
    • minimize: remove empty objects (defaults to true)
    • transform: a transform function to apply to the resulting document before returning
    • depopulate: depopulate any populated paths, replacing them with their original refs (defaults to false)
    • versionKey: whether to include the version key (defaults to true)

    so for example you can say

    Model.findOne().exec((err, doc) => {
       if (!err) {
          doc.toObject({ getters: true })
          console.log('doc _id:', doc._id) // or title
       }
    })
    

    and now it will work

提交回复
热议问题