最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jan 19, 2013 at 0:55 Kendall Frey asked Jan 18, 2013 at 21:20 Kendall FreyKendall Frey 44.3k21 gold badges111 silver badges150 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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 });
发布评论

评论列表(0)

  1. 暂无评论