node.js - 使用 nodejs 更新 mongoDB 集合 // throw new TypeError('更新文档需要原子操作符');
问题描述
所以我能够使用此代码使用 nodejs / mongoDB 创建一个集合
// create a collection and inserting the object
dbo.collection('employees').insertOne(myobj, function(err, res) {
//if there is an error throw error message
if (err) throw err;
// print out if collection is created
console.log(colors.green("Collection created ✓"),'\n','\n',companyMotto, '-',
subDomain,'\n','\n');
//close the db
db.close();
});
我试图找出一个代码来更新整个集合,如果他们的集合已经存在使用这个
// create a collection and inserting the object
dbo.collection('employees').updateOne(myobj, function(err, res) {
//if there is an error throw error message
if (err) throw err;
// print out if collection is updated
console.log(colors.green("Collection updated ✓"),'\n','\n',companyMotto, '-',
subDomain,'\n','\n');
//close the db
db.close();
});
但我得到一个错误“......抛出新的TypeError('更新文档需要原子运算符');” 任何帮助将不胜感激
解决方案
如果你想创建一个集合,你应该只调用createCollection
。insertOne
用于将文档插入到集合中,并updateOne
用于更新集合中的特定文档
Update document requires atomic operators
表示不提供更新操作。所以 mongodb 不知道你希望如何更新文档。例如$set
更新一个值,$push
将一个值推入一个数组
您可以参考 nodejs 文档以查看updateOne
应该如何调用。
updateOne(filter, update, options, callback)
见: https ://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#updateOne
推荐阅读
- r - data.table 的列可以有更多类吗?我想将日期列中某些观察的日期更改为“越界”
- php - 为什么访问 .php 文件时会出现 503 错误?
- javascript - 没有画布的 JavaScript 图像处理
- javascript - 正则表达式 - 'A,B','C'
- c++ - 联系侦听器不适用于向量的多个成员
- caffe - 如何使用以下链接中提供的预训练模型(.caffemodel 文件)?
- amazon-web-services - AWS IoT ,包含“特殊”字符的基本摄取和规则名称
- python - 解析之前有标签的所有元素
- ios - 如何在 SwiftUI 中结合可折叠行使用 List 自定义行内部内容?
- javascript - 在 GraphQL 查询中分组后如何限制和跳过标签列表页面的分页?