【问题标题】:Post Multiple Objects Inside Express Route在 Express Route 内发布多个对象
【发布时间】:2020-05-10 02:24:29
【问题描述】:

我想在快速路线内将多个对象发布到我的 mongo 数据库。目前,当我将其作为单个对象(即一个赌场)进行操作时,一切正常,请参见下文,但不是重复这样做一百万次,有人可以帮助我将其作为一个巨大的数据转储进行,以便我可以发布所有我的赌场?

这是我的路线,适用于发布单个对象:

router.post('/post', async (req, res) => {
console.log(req.body);
const casinoD = new Casino({
    casino: req.body.casino,
    table_and_other: req.body.table_and_other,
    poker: req.body.poker,
    slot_machines: req.body.slot_machines,
    total_gaming_win: req.body.total_gaming_win,
    year: req.body.year,
    month: req.body.month,
    combined_date: req.body.combined_date
})

try {
    const newCasino = await casinoD.save()
    res.status(201).json(newCasino)
} catch (err) {
    res.status(400).json({ message: err.message})
}
})

我也知道 mongoimport 是一种更好的方法 - 但是它本身就有问题。

谢谢

【问题讨论】:

  • 除了您现在拥有的单条目逻辑之外,还实现处理作为数组的请求的逻辑。类似const casinos = req.body.casinos; for (let casino of casinos) { // build a single object here and save it to the db }

标签: javascript database mongodb express mongoose


【解决方案1】:

就像@JDunken 所说,您可以将 POST 主体作为数组进行迭代并批量插入。你会想要使用 insertMany 速度。要插入数百万条记录,您可能希望合理限制每个请求的记录数,并批量发送 API 请求。验证是可选的,因为 Mongoose 将根据模式运行验证。这取决于您希望如何处理验证错误。请务必阅读orderedrawResult 选项。

router.post('/post', async (req, res) => {
  // you should sanity check that req.body is an array first, depending on how robust you want error handling to be
  const casinos = req.body.filter(input => isValid(input));

  try {
      const insertedCasinos = await CasinoModel.insertMany(casinos, { ordered: false });
      res.status(201).json(insertedCasinos)
  } catch (err) {
      res.status(400).json({ message: err.message})
  }
})

const isValid(input) {
    let valid = true;
    // implement input validation
    return valid;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多