【问题标题】:Node.js: Document returning undefined - MongooseNode.js:文档返回未定义 - Mongoose
【发布时间】:2011-12-08 22:27:54
【问题描述】:
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 在文档中,为什么会返回 undefined?

编辑:

我将 subdomain_id 添加到 Schema 并且它现在可以工作 (item.subdomain_id),但是,我没有得到子域文档,只有 ID。我想获得item.subdomain 并能够在其上调用方法。

谢谢

【问题讨论】:

  • 输入是否正确? _id 和 subdomain_id 不是有效的 json - 它们既不是字符串也不是数字。

标签: javascript mongodb node.js coffeescript


【解决方案1】:

如果您存储的是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

【讨论】:

    【解决方案2】:

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

    它看起来是这样的:

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

    我忘记并且没有考虑的是返回对象将是一个数组。这是因为您的 find 查询可以轻松且经常包含多个对象。因此,您需要枚举结果,或者如果您的查询只需要 findOne(我们没有使用 findOne),您可以像这样简单地调用对象 0:

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

    我希望这会有所帮助,如果您仍然遇到问题,请告诉我们。

    【讨论】:

      猜你喜欢
      • 2012-11-29
      • 2020-10-12
      • 2020-08-24
      • 2020-07-11
      • 2020-10-26
      • 2015-11-14
      相关资源
      最近更新 更多