无法访问猫鼬响应的对象属性 [英] Can't access object property of a Mongoose response
问题描述
我正在node.js上运行这段代码
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)第一个console.log返回完整文档
1) The first console.log return the full document
2)第二个console.log返回未定义
2) The second console.log return undefinied
我不明白为什么.
我需要执行类似的操作
var participants = docs.map(function(d){return d.user_id})
我该如何实现?我想念什么?
How can I achieve that? What am I missing ?
推荐答案
我怀疑您要获取的值不在您的Schema
中,而是存储在您的数据库中.
I suspect the value you are trying to get is not in your Schema
but is stored in your database.
您从那里有两个解决方案.您可以将entity_id
添加到Schema
,Mongo将能够将其绑定到收到的Document
对象.这是推荐的方法.
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.
或者您可以绕过猫鼬Schema
并使用docs[0]._doc.entity_id
访问存储在数据库中的原始文档.除非您知道自己在做什么,否则我不建议您使用这种解决方案.
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.
这篇关于无法访问猫鼬响应的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!