首页 > 解决方案 > 使用 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('更新文档需要原子运算符');” 任何帮助将不胜感激

标签: node.jsmongodb

解决方案


如果你想创建一个集合,你应该只调用createCollectioninsertOne用于将文档插入到集合中,并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


推荐阅读