使用http查询字符串作为数据库对象node.js/express [英] Using http query string as a database object node.js/express
问题描述
使用node.js/express/mongodb进行实验.
Experimenting with node.js / express / mongodb.
我正在使用
http://localhost:3000/models/save?model = {"name :"等等等等}
http://localhost:3000/models/save?model={"name":"blah blah blah"}
将测试JSON对象传递到快速路由/models/save,以保存到mongodb.除了collection.insert语句会返回未定义"错误外,其他所有功能都可以正常工作.
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.
我认为必须是var model = req.query.model从查询字符串中提取的参数;格式不正确.有什么想法吗?
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?
代码如下:
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;
推荐答案
请尝试以下操作:
var model = JSON.parse(req.query.model);
代替行
var model = req.query.model;
JSON.parse
方法解析JSON字符串表示形式(在您的情况下为model
请求查询参数),并返回Javascript对象,您可以在插入过程中使用它.
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.
我希望它能有所帮助.
这篇关于使用http查询字符串作为数据库对象node.js/express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!