0

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);
});
vamsiampolu
  • 6,328
  • 19
  • 82
  • 183

1 Answers1

0

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){
Will Shaver
  • 12,471
  • 5
  • 49
  • 64
  • I am using the mongojs module that comes with npm.I dont know what mongoose is,And the rest of your assumptions are correct.I would like to create or get the markers collection and insert the data. – vamsiampolu Mar 06 '14 at 16:56
  • You probably could simply use the native mongodb drivers instead of the mongojs project, unless it does something you need. https://github.com/mongodb/node-mongodb-native You'll note that the mongojs project uses these drivers. – Will Shaver Mar 06 '14 at 17:02
  • What do you reckon am I doing wrong while using the mongojs module? – vamsiampolu Mar 06 '14 at 17:07
  • You're sending it a string, it wants an object. Just like I said in the answer. – Will Shaver Mar 06 '14 at 17:09
  • i understand what you are saying,I changed my code to use `express.bodyParser` to get the `data` as an `oject` – vamsiampolu Mar 13 '14 at 17:09