Node.js:文档返回未定义 - Mongoose [英] Node.js: Document returning undefined - Mongoose

查看:213
本文介绍了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',
indicating:'234',
number:'12345678',
subdomain_id:4e9b532b01c642bf4a000003}

undefined
undefined
旧金山

code> item.subdomain_id 如果在文档中则返回undefined?



编辑:



我添加了subdomain_id到模式,它现在工作(item.subdomain_id),但是,我没有获取子域文档,只有ID。我想获得 item.subdomain ,并且可以调用它的方法。



感谢

解决方案

所以我只是寻找同一个问题的答案。我正在做的是使用Mongoose的find(通过对象继承),以便使用json查询查询。



它是什么样子:

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

我忘记了,没有考虑到返回对象将是一个数组,这是因为你的查询查询可以容易地,经常包括多个对象因为这个,你需要枚举你的结果,或者如果你的查询只需要findOne(我们没有使用findOne),你可以简单地调用对象0像这样:

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

我希望这有帮助,让我们知道,如果你仍然有问题。


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

解决方案

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:

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:

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.

这篇关于Node.js:文档返回未定义 - Mongoose的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆