简体   繁体   English

使用node.js在mongoDB中处理文档

[英]insterting documents in mongoDB using node.js

i have following code of node.js where by it connects to mongoDB and i would like to insert the message displayed at node.js console in to collection called "mytable". 我有以下node.js的代码,其中它连接到mongoDB,我想将node.js控制台上显示的消息插入到名为“mytable”的集合中。 The problem i am facing is it is successfully connecting to mongoDB and it also inserts the message which is displaying at node.js console but instead of insterting as one full document it is inserting as characters. 我面临的问题是它成功连接到mongoDB,它还插入了在node.js控制台上显示的消息,而不是作为一个完整的文档插入它作为字符插入。 why it is so happening? 为什么会这么发生? pls help 请帮助

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

            });
        }); 


});

my node console display output as 我的节点控制台显示输出为

db connected at127.0.0.1 : 27017
Inserted in to database

while checking 'mytable' mongo shell with command 用命令检查'mytable'mongo shell

db.mytable.find.forEach(printjson)

it is showing following output 它显示以下输出

{

"_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"

}

Please help i want only one entry ie 'db connected at 127.0.0.1 : 27017' to be instertd in to mytable as single document. 请帮助我只想要一个条目,即'db connected at 127.0.0.1:27017'作为单个文档进入mytable。

Mongo treats the string you're trying to insert as a BSON document (and hence an object) and iterates it's properties treating them as document fields. Mongo将您尝试插入的string视为BSON文档 (因此也是对象)并迭代它将其作为文档字段处理的属性。

Try inserting an actual object with the value you want as property: 尝试使用您想要的值作为属性插入实际对象:

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