Can't access object property of a Mongoose response

后端 未结 3 1649
情歌与酒
情歌与酒 2020-12-03 18:55

I\'m running this code on node.js

var mongoose = require(\'mongoose\');
mongoose.model(\'participant\',new mongoose.Schema({},{ collection : \'forumParticipa         


        
相关标签:
3条回答
  • 2020-12-03 19:13
    Partipant.find({entity_id: 0})
    

    The above find() returns the array of documents from DB

    You can access the value of each record

    docs.map((d)=>{
        console.log(d.get('user_id'))
    })
    
    0 讨论(0)
  • 2020-12-03 19:24

    Mongoose does funky stuff when it comes to accessing model properties. Your best bet whenever you're having problems, is either to use .lean() as part of your query, or call .toObject() on the output to convert the model into a plain JS object.

    e.g. using .toObject()

    Participant.find({entity_id: 0}, function (err, docs) {
       console.log(docs[0].toObject());
       console.log(docs[0].toObject().entity_id)
    });
    

    e.g. using lean()

    Participant.find({entity_id: 0}).lean().exec(function (err, docs) {
       console.log(docs[0]);
       console.log(docs[0].entity_id)
    });
    
    0 讨论(0)
  • 2020-12-03 19:30

    I suspect the value you are trying to get is not in your Schema but is stored in your database.

    You have two solutions from there. You can either add entity_id to your Schema and Mongo will be able to bind it to the Document object you receive. This is the recommended way.

    Or you can bypass mongoose Schema and access the raw document stored in the database with docs[0]._doc.entity_id. I don't recommend this solution unless you know what you're doing.

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