Mongoose/MongoDB result fields appear undefined in Javascript

前端 未结 10 2222
囚心锁ツ
囚心锁ツ 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:28

    If you only want to get the info without all mongoose benefits, save i.e., you can use .lean() in your query. It will get your info quicker and you'll can use it as an object directly.

    https://mongoosejs.com/docs/api.html#query_Query-lean

    As says in docs, this is the best to read-only scenarios.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 20:36

    Make sure that you have defined title in your schema:

    var MyCollectionSchema = new mongoose.Schema({
        _id: String,
        title: String
    });
    
    0 讨论(0)
  • 2020-11-27 20:36

    You don't have whitespace or funny characters in ' title', do you? They can be defined if you've quoted identifiers into the object/map definition. For example:

    var problem = {
        ' title': 'Foo',
        'content': 'Bar'
    };
    

    That might cause console.log(item) to display similar to what you're expecting, but cause your undefined problem when you access the title property without it's preceding space.

    0 讨论(0)
  • 2020-11-27 20:38

    I think using 'find' method returns an array of Documents.I tried this and I was able to print the title

    for (var i = 0; i < doc.length; i++) {
       console.log("iteration " + i);
       console.log('ID:' + docs[i]._id);
       console.log(docs[i].title);
    }
    
    0 讨论(0)
  • 2020-11-27 20:38

    Are you initializing your object?

    function MyObject()
    {
        this.Title = "";
        this.Content = "";
    }
    
    var myo1 = new MyObject();
    

    If you do not initialize or have not set a title. You will get undefined.

    0 讨论(0)
提交回复
热议问题