【问题标题】:Mongoose retrieve array from subDocumentMongoose 从 subDocument 中检索数组
【发布时间】:2021-11-20 21:44:36
【问题描述】:

我正在尝试获取给定用户拥有的所有股票的数组。

...

const user = await User.findById(verified._id);
if (!user) {
  return next(new ErrorLibrary('No user found', 401));
}

这是我用于检索用户 ID 的代码。下一步(我坚持)是获取与用户对应的所有股票的数组。

我已尝试关注

const stock = await User.stocks.findById(req.params.id);
if (!stock) {
  return next(new ErrorLibrary('No stock found', 401));
}

OUTPUT: 
"Cannot read properties of undefined (reading 'findById')"
[
  {
    "_id":"61534b363e5f39d6ce2c2c57",
    "firstName":"firstname",
    "lastName":"lastname",
    "email":"email",
    "password":"$2a$10.......",
    "tokenVersion":0,
    "stocks":[
      {
        "ticker":"TEST",
        "lots":[
          {
            "per_share_cost":1220,
            "quantity":2,
            "_id":"6153608867fae1373d272a4a",
          }
        ],
        "_id":"6153608867fae1373d272a49"
      }
    ],
    "__v":0
  }
]

【问题讨论】:

    标签: node.js json mongodb mongoose


    【解决方案1】:

    试一试

    await User.find({applyYourConditionHere});
    

    【讨论】:

    • 那么我检索子文档的条件是什么?文档显示了这一点: const doc = parent.children.id(_id);但我得到与上面相同的输出错误
    • 在尝试您的建议时,我只收到了一个用户,该用户的股票 id 为 req.params.id... 我想获得一个仅包含股票的数组
    • 您的答案可以通过额外的支持信息得到改进。请“编辑”以添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
    猜你喜欢
    • 2016-03-27
    • 2019-10-22
    • 1970-01-01
    • 2017-07-26
    • 2016-09-14
    • 1970-01-01
    • 2019-05-04
    • 2015-07-23
    • 1970-01-01
    相关资源
    最近更新 更多