【问题标题】:How to indicate an update with findAndModify method in MongoDB?如何在 MongoDB 中使用 findAndModify 方法指示更新?
【发布时间】:2018-05-27 17:08:50
【问题描述】:

我正在开发一个使用 MongoDB 和 Express.js 的应用程序。

我正在创建一个 post 处理程序,它使用玩具的新建议名称(被推送到包含其他建议名称的 id 的 nameIds 数组)更新玩具(通过其 id 找到):

router.post('/names', (req, res) => {
  const toyId = req.body.toyId;
  const name = req.body.newName;

  mdb.collection('names').insertOne({ name }).then(result =>
   mdb.collection('toys').findAndModify({
     query: { id: toyId },
     update: { $push: { nameIds: result.insertedId } },
     new: true
   }).then(doc =>
     res.send({
       updatedToy: doc.value,
       newName: { id: result.insertedId, name }
     })
   )
  )
});

但是,当我测试这个时,我收到了这个错误:

name: 'MongoError',
message: 'Either an update or remove=true must be specified',
ok: 0,
errmsg: 'Either an update or remove=true must be specified',
code: 9,
codeName: 'FailedToParse'

我对 MongoDB 并不陌生,但这个简单的调用让我感到困惑。

感谢您提供的任何帮助!

【问题讨论】:

标签: mongodb


【解决方案1】:

这是 mongo shell 的格式。使用 mongo 驱动程序,您可以使用以下参数调用:

.findAndModify( //query, sort, doc, options, callback
  { id: toyId }, //query
  [], //sort
  { $push: { nameIds: result.insertedId } }, // doc update
  { new: true }, // options
  function(err,result){ //callback
    if (err) {
      throw err
    } else {
      res.send({
        updatedToy: result.value,
        newName: { id: result.insertedId, name }
      })    
    }
  }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2017-03-11
    • 1970-01-01
    • 2014-08-11
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多