javascript – 节点JS:不插入mongodb

所以我正在关注tutsplus.com上的Node.js教程,这个课程到目前为止一直很棒.

我正在接受有关MongoDB的教训,而且我有点失意了.我不确定为什么这对我不起作用,因为它在视频中工作,我的代码是相同的.我能想到的是,自一年前开课以来,已经有了更新.

从尝试在各个点的console.log我认为数据在开始时没有正确插入,因此没有返回任何内容.

除了cursor.toArray()的回调之外,所有内容似乎都按预期触发.

我正在学习节点和mongodb,所以如果我犯了一个明显的错误,请耐心等待.

我已被指示编写以下文件,然后在命令行中执行它.

编辑:

我已将问题缩小到插入脚本.通过CLI插入数据时,它将检索回来.

var mongo = require('mongodb'),
    host = "127.0.0.1",
    port = mongo.Connection.DEFAULT_PORT,
    db = new mongo.Db('nodejsintro', new mongo.Server(host, port, {}));

db.open(function(err){
    console.log("We are connected! " + host + " : " + port);

    db.collection("user", function(error, collection){

        console.log(error);

        collection.insert({
            id: "1",
            name: "Chris Till"
        }, function(){
                console.log("Successfully inserted Chris Till")
        });

   });

});

最佳答案 你确定你真的连接到mongo?

当你从cli连接到mongo并输入’show dbs’时,你看到nodejsintro吗?

该集合是否存在?

另外,从你的代码

db.open(function(err){
    //you didn't check the error
    console.log("We are connected! " + host + " : " + port);

    db.collection("user", function(error, collection){
        //here you log the error and then try to insert anyway
        console.log(error);

        collection.insert({
            id: "1",
            name: "Chris Till"
        }, function(){
                //you probably should check for an error here too
                console.log("Successfully inserted Chris Till")
        });

   });

});

如果您已经调整了日志记录并确定没有收到任何错误,那么让我们尝试更改一些连接信息.

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('nodejsintro', server);

db.open(function(err, db) {
    if (!err) {
        console.log("Connected to 'nodejsintro' database");
        db.collection('user', {strict: true}, function(err, collection) {
            if (err) {
                console.log("The 'user' collection doesn't exist. Creating it with sample data...");
                //at this point you should call your method for inserting documents.
            }
        });
    }
});
点赞