Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - Error when inserting a document into MongoDB via Node.js

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...