简体   繁体   English

Node.js:文档返回未定义状态-猫鼬

[英]Node.js: Document returning undefined - 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

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? 如果item.subdomain_id在文档中,为什么返回未定义?

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. 我将subdomain_id添加到架构中,并且现在可以使用(item.subdomain_id),但是,我没有得到子域文档,只有ID。 I want to get item.subdomain and be able to call methods on it. 我想获取item.subdomain并能够对其调用方法。

Thanks 谢谢

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. 我正在做的是使用Mongoose的find(通过对象继承),以便使用json find查询。

What it looked like was this: 看起来是这样的:

User.find({email:req.body.email}).exec(function(err,user){
  console.log(user.email);
}

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: 因此,您将需要枚举结果,或者如果您的查询仅预期为findOne(并且我们未使用findOne),则可以像这样简单地调用对象0:

User.find({email:req.body.email}).exec(function(err,user){
  console.log(user[0].email);
}

I hope this helps, let us know if you are still having trouble. 希望对您有所帮助,让我们知道您是否仍然遇到麻烦。

If you're storing an ObjectID , not embedded documents, you need to use the populate() function to grab the referenced objects: 如果存储的是ObjectID而不是嵌入式文档,则需要使用populate()函数来获取引用的对象:

Phone.find({number : "12345678"}).populate('subdomain_id').run (err, phones) ->
  for phone in phones
    console.log phone

http://mongoosejs.com/docs/populate.html http://mongoosejs.com/docs/populate.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM