簡體   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