猫鼬-如何从对象数组中获取值?

时间:2019-05-27 18:48:52

标签: node.js mongoose

我实施了以下方案:

const UserSchema = new mongoose.Schema({
  statement: [
      {
        date: Date,
        description: String,
        amount: SchemaTypes.Double,
        balance: SchemaTypes.Double
      }
    ],
});

我想获取最后一个语句数组对象的余额。如果我查询以下内容:const statement = await User.findById(req.params.id).select("statement");,它将返回:

{
  "_id": "5cbb934d834d00a955a74081",
  "statement": [
    {
      "date": "2019-05-27T18:15:24.022Z",
      "description": "Account opening",
      "amount": 0,
      "balance": 0
    }
  ]
}

但是,如果我console.log(statement.statement)获得了Mongoose对象属性而不是存储在数组中的对象,那么我将无法执行statement.statement[-1]

我该如何解决?

预先感谢

1 个答案:

答案 0 :(得分:0)

您应该使用toJSON方法来获取普通的JSON对象

https://mongoosejs.com/docs/guide.html#toJSON

此外,您不能使用-1作为数组的索引,要获取数组的最后一个元素,您可以像这样

array.slice(-1)[0] 

如果数组为空,这将返回undefined

相关问题