gpt4 book ai didi

mongodb - 如何在 MongoDB 中使用 findAndModify 方法指示更新?

转载 作者:可可西里 更新时间:2023-11-01 10:48:09 28 4
gpt4 key购买 nike

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

我正在创建一个后处理程序,它使用玩具的新建议名称(被推送到包含其他建议名称的 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 的新手,但这个简单的调用让我感到困惑。

感谢您提供的任何帮助!

最佳答案

这是 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 }
})
}
}
)

关于mongodb - 如何在 MongoDB 中使用 findAndModify 方法指示更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47799318/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com