简体   繁体   English

通过Node.js将文档插入MongoDB时出错

[英]Error when inserting a document into MongoDB via Node.js

I'm trying to insert a document into MongoDB in Node.js. 我正在尝试在Node.js中将文档插入MongoDB。 I have read from the DB successfully, and added documents via the command-line interface. 我已成功读取数据库,并通过命令行界面添加了文档。 However, I can't insert a document from JavaScript. 但是,我无法从JavaScript插入文档。 If I do, I get an error: 如果我这样做,我会收到一个错误:

Error: Cannot use a writeConcern without a provided callback 错误:如果没有提供的回调,则无法使用writeConcern

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? 我做错了什么,我应该怎么做呢?

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. 您需要为insert调用提供回调函数,以便该方法可以将插入期间发生的任何错误传达给您。

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: 或者,如果您真的不关心插入是否成功,请在options参数中传递写入关注值0:

db.collection("test").insert({ str: "foobar" }, { w: 0 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM