node.js - 如果存在,如何更新文档,如果在 mongodb 中不存在,如何将其插入?
问题描述
这个问题与其他类似问题不同,因为 { upsert: true } 选项没有提供所需的输出。我想更新/插入以下文档:
{
_id: {
playerId: '1407081',
tournamentId: '197831',
matchId: '1602732'
},
playerName: 'abcd',
points: -5
}
执行下面给出的代码后,
await Points.findOneAndUpdate(
{
"_id": playerStatsObjForDB._id
},
{
playerStatsObjForDB
},
{
upsert: true
}
);
//where playerStasObjForDB is same as object mentioned in top.
如果文档不存在,则插入以下文档:
{
"_id": {
"playerId":"1407081",
"tournamentId":"197831",
"matchId":"1602732"
},
"__v":0,
}
我正在使用猫鼬,但非常感谢任何帮助。
解决方案
MongoDB upsert 的工作方式如下:
db.products.updateMany(
{ _id: 6 },
{ $set: {price: 999} },
{ upsert: true}
)
所以基本上第一个参数是查询本身,就像你做的一样,但第二个应该是你想要修改的更新,你应该使用像 $set 这样的 MongoDB 运算符。相反,您似乎将整个对象嵌入其中而没有修改。
推荐阅读
- python - BeautifulSoup - “找不到树生成器”错误,我错过了什么?
- javascript - 如何在 React js 中以 1 颗星和第二行 2 颗星的模式打印 5 次星星?
- reactjs - 如何通过链接组件在反应中测试屏幕转换
- serial-port - 是否可以通过 Web Serial API 访问虚拟串口?
- python - 为什么代码在Python中中途停止运行
- flutter - 如何在没有 cli 的情况下使用 amplify-flutter
- logging - 为什么我的 nifi 不能将日志分成小部分?
- amazon-web-services - 哪一个在 redshift 中性能更高 - 截断后跟插入或删除并创建表为?
- netty - 带有 ReactorClientHttpConnector 的 Netty:如何在不使用已弃用的 tcpConfiguration 的情况下设置 readTimeout、writeTimeout 和 connectTimeout
- python - 如何在 Python 中使用插入排序根据他们的分数对学生列表进行排序