Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

node.js - Can't access object property of a Mongoose response

I'm 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 return the full document

2) The second console.log return undefinied

I don't understand why.

I need to perform something like

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

How can I achieve that? What am I missing ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...