【问题标题】:Querying a collection with matching IDs from an array of JSON objects with Mongoose使用 Mongoose 从 JSON 对象数组中查询具有匹配 ID 的集合
【发布时间】:2020-10-24 17:18:24
【问题描述】:

我有一个数据库集合,其中每一行都有一个与之关联的唯一 ID。我希望能够查询我的数据库并将其中的数据与数组中每个对象中的 ID 匹配。 _ids 是一个字符串。

集合示例:

"_id" : "453241", 
"name" : "Item1", 

"_id" : "621984", 
"title" : "Item2", 

"_id" : "832127", 
"title" : "Item3", 

对象看起来像这样:

query = [{"_id":"621984","quantity":"3"},{"_id":"832127","quantity":"2"}]

所需的输出将是这样的(我不想将数量写入数据库):

output = [{"_id":"621984","Item2", "quantity":"3"},{"_id":"832127", "Item3" ,"quantity":"2"}]

从其他线程中,我了解到我们必须使用$is 来匹配数据。就像本例中的 MongoDB select where in array of _id? 一样,但问题在于他们使用的是 ID 数组。而且我不确定我们如何将数量附加到这个值。

我还考虑过遍历数组内所有对象的循环,然后搜索数据库。并将输出附加到数组中。这将是最有益的,因为我希望整体输出也包括数量。 在这种情况下,console.logging 结果有效并输出指定的 ID 表,但是当尝试将值附加到输出然后返回时,它不起作用并返回一个空数组。

output = []
for (item in query) {
    collection.find({"id": item._id}).then((result) => { output.push(result + item.quantity) })
}
return output

任何想法或帮助将不胜感激。

【问题讨论】:

  • 你的阵列是什么样的?
  • 您确定要在output 变量中定义上述结果,因为它看起来无效?

标签: node.js mongodb mongoose


【解决方案1】:

就效率而言,我在自己的实现中遇到了非常相似的情况。我最终采用的方法(以一对多关系授予)如下。

  • 在 Mongoose 查询之前将 Id 隔离到一个数组中

let ids = []
for (object in query) {
  ids.push(query[object]._id)
}

collection.find({ id : $in : ids }).then((result) => {
  for (let i in result) {
    for (let j in query) {
      if (result[i]._id === query[j]._id) {
        query[j].name = result[i].name
      }
    }
  }
}).catch((error) => {
  console.log("Query Error")
})
  • 此外,在上面的示例中,获取 Id 数组将需要 Mongo $in 运算符搜索数组并返回适当的集合项。

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 2015-12-23
    • 1970-01-01
    • 2021-09-27
    • 2021-07-02
    • 2021-07-08
    • 2022-11-24
    • 1970-01-01
    • 2018-04-26
    相关资源
    最近更新 更多