【问题标题】:In a series of MongoDB inserts I want to reference the objectId of the previously inserted item在一系列 MongoDB 插入中,我想引用先前插入的项目的 objectId
【发布时间】:2018-01-24 18:19:21
【问题描述】:

我想在 MongoDB 中插入一系列文档,其中每个文档都必须引用之前插入的条目。认为 Domino 是下一个掉落的物品,它会意识到它被撞倒的物品。

说,我在数据库中插入三个多米诺骨牌,我想达到以下结果(_id 是由 MongoDB 在插入时生成的)。

{ _id: '1', parentId: null },
{ _id: '2', parentId: '1' },
{ _id: '3', parentId: '2' },

我尝试了以下方法:

let parentId = null;
dominos.map(domino => {
  domino.parentId = parentId;
  return storeItem(domino)   // calls Model.create and returns _id
    .then((result) => {
      parentId = result; // a console.log would print the latest _id
    })
    .catch(error => error);
})

问题是在 .then 子句中接收到的 parentId 没有向上传播,因此即使在插入第二个和第三个项目之后,domino.parentId = parentId 仍然为空。

我确信我在范围或承诺方面遗漏了一些小东西。任何建议如何让它发挥作用,或者可能是另一种更可行的方法,我们将不胜感激。

问候 -行动

【问题讨论】:

  • parentId = result 将在所有多米诺骨牌被映射后发生。你需要链接你的承诺。您正在异步进行插入并且彼此独立。您只能在插入前一个元素之后再插入一个元素。
  • 您也可以在客户端生成所有 id 并同时插入准备好的数据。无需等待之前的插入。

标签: javascript node.js mongodb mongoose ecmascript-6


【解决方案1】:

安装异步依赖

npm install --save async

试试这个

const async = require('async')

let parentId = null

async.each(dominos, 
    function(domino, callback) {
        domino.parentId = parentId;
        storeItem(domino)
        .then((result) => {
            parentId = result
            callback()
        })
    }, function (err) {
        console.log('success')
    })

【讨论】:

【解决方案2】:

正如@Mikey 在另一个答案中的评论中所建议的那样:

在这种情况下,也许应该使用 async.eachSeries()

使用 async.eachSeries 确实对我有用 - 谢谢!

-行动

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2018-09-15
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多