Node.js 插入到查询执行操作的回调函数中

Node.js 插入到查询执行操作的回调函数中,node.js,mongodb,node-mongodb-native,Node.js,Mongodb,Node Mongodb Native,错误:如果没有提供的回调,则无法使用writeConcern。创建到数据库的连接时,您必须提供对写入函数的回调,因为您有writeConcern 1(默认设置)。您的代码应该如下所示: db.createCollection("category",function(errDb,collection){ collection.findOne({name:"test"},function(err,value){ if(value == null) {

错误:如果没有提供的回调,则无法使用writeConcern。创建到数据库的连接时,您必须提供对写入函数的回调,因为您有writeConcern 1(默认设置)。您的代码应该如下所示:

db.createCollection("category",function(errDb,collection){
    collection.findOne({name:"test"},function(err,value){
        if(value == null)
        {
            collection.insert({name:"test"})
        }
    })
})
但是,如果您不想激活写关注点,只想在创建连接时使用已完成的函数进行插入,则必须像这样进行连接

db.createCollection("category",function(errDb,collection){
    collection.findOne({name:"test"},function(err,value){
        if(value == null)
        {
            collection.insert({name:"test"}, function(err, docs){
                if (err) //do anything you want to do when there is an error
                // Here you write code for what you would do when the documents were sucessfully       inserted into the collection

            });
        }
    })
})
在这里,我将writeConcern设置为0。这将阻止mongo.db向您确认插入或更新是否成功。现在您可以使用
collection.insert({name:“test”})


请注意,在使用w:0时要小心,因为您不想将其用于需要确定插入或更新的数据,因为写入失败可能会丢失一些数据。

缺少回调函数的可能重复。正如副本所示,您需要提供一个回调函数。您的
insert
调用不使用回调。
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/integration_test_?", {
    db: {
      w : o
    }
  }, function(err, db) {
  test.equal(null, err);
  test.ok(db != null);

// Do anything like you were doing here
}