【问题标题】:Mongoose can't access to data with findOne or find methodMongoose 无法使用 findOne 或 find 方法访问数据
【发布时间】:2023-03-07 18:10:01
【问题描述】:

我正在尝试访问amount。我可以看到数据:

架构:

var schema = mongoose.Schema({
    investors : {
        id        : String, 
        amount     : Number,
        user_id      : String,
        inv_profit : Number
    }

});

命令

invs2.findOne({}, function(err, data){

        console.log(data)
})

输出:

{ _id: 54159a1c291df572283fa4de,
  investors: 
   [ { inv_profit: 0,
       user_id: 'userID',
       amount: 1.2,
       id: '1410701852660' },
     { inv_profit: 0,
       user_id: 'userID',
       amount: 1.2,
       id: '1410701858752' } ] }

invs2.findOne({}, function(err, data){

        console.log(data.investors)
})

输出:

[ { id: '1410701852660',
    amount: 1.2,
    user_id: 'userID',
    inv_profit: 0 },
  { id: '1410701858752',
    amount: 1.2,
    user_id: 'userID',
    inv_profit: 0 } ]

但是当我尝试访问data.investors[0].amount 时,我得到了undefined

即使data.investors.length 也在返回undefined

invs2 集合中只有一个条目。

【问题讨论】:

  • 是的,我已经添加了架构。

标签: json node.js mongodb express mongoose


【解决方案1】:

investors 如果是子文档数组,则应在架构中定义为数组:

var schema = mongoose.Schema({
    investors : [{
        id        : String, 
        amount     : Number,
        user_id      : String,
        inv_profit : Number
    }]
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 2021-10-12
    • 2014-01-24
    • 2014-12-15
    • 1970-01-01
    • 2019-02-24
    • 2012-12-27
    • 2016-02-10
    相关资源
    最近更新 更多