使用 http 查询字符串作为数据库对象节点。js/express

Using http query string as a database object node.js/express

正在试验 node.js / express / mongodb。

我正在使用

http://localhost:3000/models/save?model={"name":"blah blah blah"}

将测试 JSON 对象传递到快速路由 /models/save 以保存到 mongodb。一切正常,除了 collection.insert 语句 returns 一个 "undefined" 错误。

我想一定是var model = req.query.model;从查询字符串中提取的参数格式不正确。有什么想法吗?

代码如下:

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 请求查询参数)和 returns Javascript 对象,然后您可以在插入过程中使用。

希望对您有所帮助。