Entering data with MongoDb and Node.js

Entering data with MongoDb and Node.js

Problem

So I’m trying to enter data into a mongodb collection with node. As far as I can tell I have access to the collection.

var collection = db.collection("whatsGoingOnEvents");
if(collection){
console.log("hitting stream");
var stream = collection.find({time: parsedObject.time, endTime: parsedObject.endTime, lon:parsedObject.lon,lat:parsedObject.lat}).stream();
console.log(stream);
stream.on("data",function(data){
    console.log("data");
    console.log(data);
    if(!data){
        collection.insert(parsedObject);
        console.log("hitting insert");
    }
});
stream.on("end",function(){
//dosomething
});
}

parsedObject may or may not have all of those fields – should it matter? I thought if the field was not there then collection.find() is just looking for time to be “undefined”, which is still technically a value.

I never hit console.log("data") so I never insert documents. I’ve been trying to follow this link.

and so am not sure why the insert is not happening. I know that nothing is being added from db.collection.stats();, which tells me the size of the collection is 0.

Oh also, this is what I’m using to connect to Mongo-

var mongo = require('mongodb').MongoClient;

EDIT–

I tried the answer below – that resulted in this error-

    lib/mongodb/connection/server.js:481
        throw err;
              ^
Error: Cannot use a writeConcern without a provided callback
    at insertAll (/Users/psanker/Google Drive/Coding/Javascript/WhatsGoingOn/node_modules/mongodb/lib/mongodb/collection.js:332:11)
    at Collection.insert (/Users/psanker/Google Drive/Coding/Javascript/WhatsGoingOn/node_modules/mongodb/lib/mongodb/collection.js:91:3)

^The above occurred because I hadn’t added a callback to the insert.

Problem courtesy of: praks5432

Solution

If your query doesn’t match any records (which would seem logical, given that you write that the collection size is 0), the data event handler will never get called (because that will only be called when there’s an actual result).

I think you’re better off with using findOne and a regular callback:

collection.findOne({ params }, function(err, result) {
  if (err)
    throw err;
  if (result === null) {
    collection.insert(parsedObject, { w: 0 });
  }
});

Or even an upsert.

Solution courtesy of: robertklep

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *