簡體   English   中英

使用node.js在mongoDB中處理文檔

[英]insterting documents in mongoDB using node.js

我有以下node.js的代碼,其中它連接到mongoDB,我想將node.js控制台上顯示的消息插入到名為“mytable”的集合中。 我面臨的問題是它成功連接到mongoDB,它還插入了在node.js控制台上顯示的消息,而不是作為一個完整的文檔插入它作為字符插入。 為什么會這么發生? 請幫助

var mongo = require("mongodb");
var dbhost = "127.0.0.1";
var dbport = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("mydb", new mongo.Server(dbhost, dbport, {}), {safe: true});
db.open(function(error){
        status = ("db connected at" + dbhost + " : " + dbport);
        console.log(status);

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

        collection.insert(status, function(error){

            if (error){
                console.log("Error : ", error.message);
            } else {
                console.log("Inserted in to database");
                } 

            });
        }); 


});

我的節點控制台顯示輸出為

db connected at127.0.0.1 : 27017
Inserted in to database

用命令檢查'mytable'mongo shell

db.mytable.find.forEach(printjson)

它顯示以下輸出

{

"_id" : objectId("5207741d193770459f068317"),
"0" : "d",
"1" : "b",
"3" : " ",
"4" : "c",
"5" : "o",
"6" : "n",
"7" : "e",
"8" : "c",
"9" : "t",
"10" : "e",

"28" : "7",
"29" : "0",
"30" : "1",
"31" : "7"

}

請幫助我只想要一個條目,即'db connected at 127.0.0.1:27017'作為單個文檔進入mytable。

Mongo將您嘗試插入的string視為BSON文檔 (因此也是對象)並迭代它將其作為文檔字段處理的屬性。

嘗試使用您想要的值作為屬性插入實際對象:

collection.insert({status: status}, function(error){

        if (error){
            console.log("Error : ", error.message);
        } else {
            console.log("Inserted in to database");
            } 

        });
    }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM