【问题标题】:MongoError $in needs an arrayMongoError $in 需要一个数组
【发布时间】:2018-02-23 15:58:49
【问题描述】:

我正在尝试从数组中获取数据,并希望将其传递给我在 $in 运算符中的 find 查询。 但它给出了一个错误说

$in 需要一个数组

const fileIds = _.get(result, 'files', []);
console.log(fileIds);
db.collection('files').find({_id: {$in: fileIds}}).toArray((err, files) => 

{
    // some statements....
}

这是 console.log(fileIds) 的输出

{ '0': 5a8f24ab281bd22cd940530b, '1': 5a8f24ab281bd22cd940530c }

在标记为重复之前,我已经看过这篇文章。

How to return the ObjectId or _id of an document in MongoDB? and error "$in needs an array"

但这些都没有帮助。所以如果有人知道答案,请帮忙。 提前致谢。

【问题讨论】:

  • 那么fileIds 是对象,而不是数组?

标签: node.js mongodb


【解决方案1】:

请这样做

在这里我使用了节点版本 6.9 支持的Object.values 或者 8 你可以通过其他方法创建数组

  const fileIds = _.get(result, 'files', []);

    db.collection('files').find({_id: {$in: Object.values(fileIds)}}).toArray((err, files) => 

    {
        // some statements....
    }

【讨论】:

  • 谢谢兄弟。它为我节省了很多时间。我还是做了很多研究..但再次感谢
猜你喜欢
  • 2014-02-28
  • 2019-06-27
  • 2014-10-27
  • 2023-03-26
  • 2020-01-25
  • 2018-05-20
  • 2021-12-06
  • 2019-03-25
相关资源
最近更新 更多