StackThis
StackThis

Reputation: 883

Convert JSON to INTeger for MongoDB?

With .post of FORM data to express/node.js

All of the values are currently stored and returned as STRings

Am looking to have one of the data values (req.body.quantity) stored as an INT

//POST
app.post('/add', function (req, res) {    

db.collection('demo').insert(

    {
        "title" : req.body.title,
        "quantity" : req.body.quantity,
    },

        function (err, doc) {

            getAll(res);

        });
});

The getAll currently looks like this:

//EXPRESS NODE.JS
function getAll(res) {

    db.collection('demo').find().sort( { quantity: 1 } ).toArray(function (err, docs) {

     // each doc should look like: { title: 'string', quantity: int}

        res.json({docs: docs});

    });
}

And the working .get:

// AJAX    
$('#getBtn').click(function() {
  $.get('http://localhost:9999').
   done(gotAllSuccess).
   fail(gotAllFailure);
});

Upvotes: 0

Views: 1240

Answers (2)

maerics
maerics

Reputation: 156434

You can use the Number(...) constructor or function.

Number("123"); // => 123

db.collection('demo').insert(
  {
    "title" : req.body.title,
    "quantity" : Number(req.body.quantity),
  },
  // ...

Upvotes: 0

ChevCast
ChevCast

Reputation: 59213

For your code I believe this will fix it for you.

"quantity" : parseInt(req.body.quantity)

However, I recommend that you look into something like Mongoose if you haven't already. It's an ORM for MongoDB and it lets you define schemas that describe how your models should look. In your case you'd be able to design a schema that looked like this:

// Define your schema somewhere where your app is first initialized.
// You'll also want to open your db connection here somewhere as well, but I'll
// let you figure that out. http://mongoosejs.com
var demoSchema = new mongoose.Schema({ title: String, quantity: Number });
var Demo = mongoose.model('Demo', demoSchema);
// You can just pass in an object literal to mongoose.model instead of
// instantiating a Schema object, but instantiating a Schema object is what
// you'd have to do if you wanted to also add virtual methods/properties.

You can also add virtual properties and virtual methods to your schema here. These properties and methods don't get stored in the database.

Then you can do this:

// Retrieve the model you created.
var Demo = require('mongoose').model('Demo');

// Request handler for POST requests to /add
app.post('/add', function (req, res) { 
    // Create a new instance of your Demo model and populate it with data.
    var newDemo = new Demo({
        title: req.body.title,
        quantity: req.body.quantity
        // quantity will be converted to a Number because the schema defines it
        // as one.
    });
    // Mongoose documents have persistence methods on them, including save
    // which will update or insert the document depending on whether or not
    // it has an _id already.
    newDemo.save(function (err, newDemo) {
        if (err) return handleError(err);
        // Models also act as the API for querying. Here we find all documents,
        // sort them by quantity ascending, then execute the query.
        // Note: mongoose's query builder syntax below uses promises to make
        // queries very readable :)
        Demo.find().sort('quantity').exec(function (err, demos) {
            if (err) return handleError(err);

            // demos is an array of Demo instances, each with the same
            // persistence methods you saw above.

            // Each demo doc's properties will adhere to the defined type
            // in the schema.
            //
            // { title: 'hello', quantity: 123}

            res.json({ docs: demos });
        });
    });
});

Upvotes: 1

Related Questions