0

I am passing parameters via post to my server. The nodejs server gives me req.body api to fetch all the parameters sent. I am planning to map that data onto a model class and then convert that model class to JSON format in order to insert it in mongo db.

How can I convert the model class in JSON format? and how can I easily map the parameters in request object to model class easily?

model.js

var mName;
var mFatherOrHusbandName;



function setName(name) {
    mName = name;
}

function getName() {
    return mName;
}

function setFatherOrHusbandName(name) {
    mFatherOrHusbandName = name;
}

function getFatherOrHusbandName() {
    return mFatherOrHusbandName;
}

module.exports={setName:setName, getName:getName, setFatherOrHusbandName:setFatherOrHusbandName}

code where I try to insert the data into db.

function insertData(request) {
    var mongoClient = mongoDB.MongoClient();

    var url = "mongo://localhost:27017/myDB";

    mongoClient.connect(url, function(err, db) {
        if(err) {
            console.error("error in connecting to MongoDB", err);
        }
        else {
            var patientsCollection = db.collection("model");

            var jsonData = // map request to model class and convert the class to JSON format;

            patientsCollection.insert([jsonData], function(err, result) {
                if(err)
                    console.error("Unable to insert into MongoDB", err);
                else {
                    console.log("Data entered successfully", result);
                }
            });
        }
    });
}
user2498079
  • 2,872
  • 8
  • 32
  • 60
  • 1
    javascript is not JSON. In particular, javascript functions are not valid JSON. If all you care about is the state of your instances, give your class a `.toJSON` method. – Jared Smith Apr 22 '16 at 13:34
  • will that convert the member variables i-e; mName & mFatherOrHusbandName in key value pairs JSON? – user2498079 Apr 22 '16 at 13:38
  • 1
    Is there any particular reason why you cannot use an object data modeling (ODM) library like [Mongoose](http://mongoosejs.com/) which provides a rigorous modeling environment for your data instead of creating the data models from scratch? – chridam Apr 22 '16 at 13:43
  • Possible duplicate of [Convert JS object to JSON string](http://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – Jared Smith Apr 22 '16 at 13:51

0 Answers0