Cannot access Mongoose response property object

I am running this code on node.js

var mongoose = require('mongoose');
mongoose.model('participant',new mongoose.Schema({},{ collection : 'forumParticipant' }));
var Participant = mongoose.model('participant');
mongoose.connect('******');

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

1) The first console.log returns the full document

2) The second .log console returns undefinied

I do not understand why.

I need to do something like

var participants = docs.map(function(d){return d.user_id})

How can i achieve this? What am I missing?

+4
source share
2 answers

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

You have two solutions from there. You can add entity_idto yours Schema, and Mongo will be able to associate it with the object Documentyou receive. This is the recommended method.

mongoose Schema , , docs[0]._doc.entity_id. , , .

+9

Mongoose , . , , .lean() , .toObject() , JS.

. .toObject()

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

. lean()

Participant.find({entity_id: 0}).lean().exec(function (err, docs) {
   console.log(docs[0]);
   console.log(docs[0].entity_id)
});
+6

Source: https://habr.com/ru/post/1607841/


All Articles