Node.js:返回未定义的文档 - Mongoose
Phone.find {number : "12345678"}, (err,phone) ->
phone.forEach (item, i) ->
console.log item
console.log item.subdomain
console.log item.subdomain_id
console.log item.city
返回:
{ _id: 4e9b614e01c642c2be000002,
city: 'San Francisco',
country: 'US',
indicative: '234',
number: '12345678',
subdomain_id: 4e9b532b01c642bf4a000003 }
undefined
undefined
San Francisco
如果 item.subdomain_id
在文档中,为什么它返回未定义?
编辑:
我将 subdomain_id 添加到架构中,它现在可以工作(item.subdomain_id),但是,我没有获得子域文档,只有 ID。我想要获取 item.subdomain
并能够调用它的方法。
谢谢
Phone.find {number : "12345678"}, (err,phone) ->
phone.forEach (item, i) ->
console.log item
console.log item.subdomain
console.log item.subdomain_id
console.log item.city
returns:
{ _id: 4e9b614e01c642c2be000002,
city: 'San Francisco',
country: 'US',
indicative: '234',
number: '12345678',
subdomain_id: 4e9b532b01c642bf4a000003 }
undefined
undefined
San Francisco
Why is the item.subdomain_id
returning undefined if it's in the document?
Edit:
I added subdomain_id to the Schema and it now works (item.subdomain_id), however, I'm not getting the subdomain document, only the ID. I want to get item.subdomain
and be able to call methods on it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要存储
ObjectID
,而不是嵌入文档,则需要使用populate()
函数来获取引用的对象:http://mongoosejs.com/docs/populate.html
If you're storing an
ObjectID
, not embedded documents, you need to use thepopulate()
function to grab the referenced objects:http://mongoosejs.com/docs/populate.html
所以我只是在寻找同一问题的答案。我所做的是使用 Mongoose 的 find (通过对象继承),以便使用 json find 查询。
它看起来是这样的:
我忘记并且没有考虑的是返回对象将是一个数组。这是因为您的查找查询可以轻松且经常包含多个对象。因此,您要么需要枚举结果,要么如果您的查询仅期望 findOne(并且我们没有使用 findOne),您可以简单地调用对象 0,如下所示:
我希望这有帮助,如果你仍然遇到麻烦。
So I was just searching for an answer to the same question. What I was doing was using Mongoose's find (through object inheritance), in order to use a json find query.
What it looked like was this:
What I forgot about and hadn't considered is that the return object will be an Array. This is because your find query can easily and often does include multiple objects. Because of this, you will either need to enumerate your results, or if your query is only expected to findOne (and we didn't use findOne), you can simply call object 0 like so:
I hope this helps, let us know if you are still having trouble.