问题
Inserting into Mongo DB using the mongojs module fails cryptically,I have two functions,setupMongoDB and pushRequestsToMongoDB(what they do is self-explanatory). I get a request from my web-page and parse the data to JSON.
The console looks like this:
created worker: 22987
created worker: 22989
created worker: 22990
created worker: 22991
{ type: 'line',geometry: '`tvtBat~_Wnaoi@_kc~BzlxZbrvdA{fw[`mw}@' }
object
[Error: connection closed]
The code that did produces the error looks like this:
var mongo=require('mongojs');
var collections=['testData'];
var dbURL='localhost:3000/mapData';
var db=mongo.connect(dbURL,collections);
var insert=function(obj)
{
db.testData.save(obj,function(err,obj){
if(err || !obj)
{
console.log(err);
}
else
{
console.log('Data successfully inserted with _id '+obj['_id']);
}
});
};
exports.insert=insert;
This is how I use the function:
var express=require('express');
var app=express();
var mongo=require('./mongo_try');
app.use(express.bodyParser());
app.post('/map',function(req,res){
var data=req.body;
console.log(data);
console.log(typeof data);
mongo.insert(data);
});
回答1:
I'm very confused at what "conn.markers.save" intends to do. Is this a mongoose call? Mongodb node native doesn't have a "save" command. Do you mean to get the "markers" collection, and then insert the data? You won't need to stringify it.
Are you using this: https://github.com/mafintosh/mongojs ?
You shouldn't have to stringify that save command either. Change this line:
conn.markers.save(obj,function(err,data){
Or if the contents of "obj" are already a string, change it to:
conn.markers.save(JSON.parse(obj),function(err,data){
来源:https://stackoverflow.com/questions/22230131/inserting-into-mongodb-using-node-js