繁体   English   中英

节点JS:未插入mongodb

[英]Node JS: Not inserting into mongodb

因此,我正在tutsplus.com上关注Node.js教程课程,到目前为止,它是很棒的。

我正在上有关MongoDB的课程,我有些不了解。 我不确定为什么这对我不起作用,因为它在视频中有效并且我的代码是相同的。 我所能想到的是,自一年前开设该课程以来,已有更新。

从尝试在各个方面尝试console.log ,我认为数据在开始时未正确插入,因此未返回任何内容。

除了cursor.toArray()的回调,一切似乎都按预期启动。

我目前正在学习node和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.
            }
        });
    }
});

暂无
暂无

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

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