Mongoose:在将数据发送给请求者之前转换数据

时间:2018-03-28 08:09:59

标签: node.js mongoose

通常,Mongoose返回从DB收到的数据。我们可以通过删除或修改某些数据的值来转换数据,然后再将其返回给请求者吗?

1 个答案:

答案 0 :(得分:0)

是的,你可以!您可以在Express(node.js)中使用中间件,因为Mongoose使用自己的返回数据对象类型,您可以使用mongooseReturn.toObject()函数将它们转换为JS对象,或者如果您有一个对象数组,那么您可以在查询中使用.lean(true)

RER。 http://mongoosejs.com/docs/api.html#query_Query-lean

参考。 https://expressjs.com/en/guide/using-middleware.html

如果您向我展示您的代码,我可以向您展示如何对其进行转换,在我的一个示例中,我正在这样做:

假设models / drug.js包含所有架构数据。然后...

路由/ drug.js:

..
..
let _middleware = require('../functions/middleware');

/* GET drugs find by comparing name. */
router.get('/search/:keyword', function(req, res, next) {
    Drugs
        .find({"name": { $regex: new RegExp("^" + req.params.keyword.toLowerCase(), "i")}})
        .limit(3)
        .lean(true)                                         //Ref. http://mongoosejs.com/docs/api.html#query_Query-lean
        .exec(function(err, drugs) {
            if (err)
                return res
                    .status(500)
                    .send(err);

            _middleware.cleanHtml(drugs, function(cleanDrug){ //no .toObject() because of multiple objects

            res
                .status(200)
                .json(cleanDrug);
            });
        });
});

然后你在这个代码上方需要的middleware.js文件中:

module.exports = {
    cleanHtml: function(drugs, callback) {
        console.log("executing: cleanHtml()");

        try {
            if (drugs instanceof Array) {                                           //in case of an Array of JSONs, add or remove elements below
                console.log("Array of MANY come in for processing.");

                for (let drug of drugs){
                    drug = html_cleanup(drug);
                }

                return callback(drugs);
            } else {                                                                //in case of single JSON object, manipulate the key-value pairs of a single instance
                drugs = html_cleanup(drugs);
                return callback(drugs);
            }
        } catch(err) {
            console.log("\n\n == EXCEPTION (@Function: "
                + arguments.callee.name + "() @File: "
                + _inbuild.get_current_file_name(__filename)
                + "): \n\n"
                + err
                + "\n\n == END-OF-EXCEPTION \n\n");

            drugs['exception'] = err.toString();  //add error to returning variable
            return callback(drugs);
        }
    },

  };
}