15

I'm trying to insert a document into MongoDB in Node.js. I have read from the DB successfully, and added documents via the command-line interface. However, I can't insert a document from JavaScript. If I do, I get an error:

Error: Cannot use a writeConcern without a provided callback

Here is my code:

var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;

MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
        if (!err) {
            db.collection("test").insert({ str: "foobar" });
        }
    });

I can't for the life of me figure out why I get this error.

What did I do wrong, and how should I do this instead?

1 Answer 1

43

You need to provide a callback function to your insert call so that the method can communicate any errors that occur during the insert back to you.

db.collection("test").insert({ str: "foobar" }, function (err, inserted) {
    // check err...
});

Or, if you truly don't care whether the insert succeeds or not, pass a write-concern value of 0 in the options parameter:

db.collection("test").insert({ str: "foobar" }, { w: 0 });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it seems to work. Can you point me to the documentation for this? All the examples I found didn't seem to be for node. I can't find any examples that work as-is.
What you're hitting is that before MongoClient was introduced, all example code typically used connections where safe-writes mode was off by default, and in that case you're code would have worked. But MongoClient enables safe mode by default. Note that the example in the insert docs notes that it's not using safe mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.