Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 i.e. 'db connected at 127.0.0.1 : 27017' to be instertd in to mytable as single document.

like image 225
user2672180 Avatar asked Apr 01 '26 17:04

user2672180


1 Answers

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.

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

        });
    }); 
like image 181
soulcheck Avatar answered Apr 03 '26 11:04

soulcheck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!