Inserting into MongoDB using Node js

倖福魔咒の 提交于 2019-12-25 02:53:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!