Experimenting with node.js / express / mongodb.
I'm using
http://localhost:3000/models/save?model={"name":"blah blah blah"}
to pass a test JSON object to the express route /models/save for saving to the mongodb. Everything works great except the collection.insert statement which returns an "undefined" error.
I think it must be that the parameter extracted from the query string by var model = req.query.model; is not in the correct format. Any ideas?
The code is as follows:
var express = require('express');
var router = express.Router();
router.get('/save', function(req, res) {
// Set our internal DB variable
var db = req.db;
var model = req.query.model;
console.log (model);
// Set our collection
var collection = db.get('models');
// Submit to the DB
collection.insert ( model, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem saving to the database.");
console.log(doc);
}
else {
console.log ("model saved");
res.send("OK")
}
});
});
module.exports = router;
Please try the following:
var model = JSON.parse(req.query.model);
instead of the line
var model = req.query.model;
JSON.parse
method parses JSON string representation (which in your case is model
request query parameter) and returns Javascript object which you can then use in your insert process.
I hope it helps some way.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments