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 ie 'db connected at 127.0.0.1 : 27017' to be instertd in to mytable as single document.
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");
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.