通过Node.js将文档插入MongoDB时出错 [英] Error when inserting a document into MongoDB via Node.js

查看:104
本文介绍了通过Node.js将文档插入MongoDB时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Node.js中将文档插入MongoDB。我已成功读取数据库,并通过命令行界面添加了文档。但是,我无法从JavaScript插入文档。如果我这样做,我收到一个错误:

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:


错误:没有提供的回调就不能使用writeConcern

Error: Cannot use a writeConcern without a provided callback

这是我的代码:

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.

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

或者,如果您真的不在乎插入是否成功,则通过写入关注options参数中的值为0:

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

这篇关于通过Node.js将文档插入MongoDB时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆