如何基于Express参数检索猫鼬模型

时间:2018-09-12 03:31:11

标签: javascript node.js mongodb express mongoose

如何动态检索名称取决于req.params.model的猫鼬模型?

这是我的架构示例

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const SmartSchema = new Schema({
SmartPriority: {
    type: String,
    required: true
},
SmartClassification: {
    type: String,
    required: true
}
});

module.exports = mongoose.model("smarts", SmartSchema);

我下面的代码不起作用。

router.delete(
"/delete/:model/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
    let { model, id } = req.params;
    model.deleteOne({ _id: id }) //model = Mongoose Model/ eg: Smart Schema
        .then(res.status(200).json({ msg: "Success" }))
        .catch(err => {
            res.status(500).send({ msg: err });
        });
}
);

1 个答案:

答案 0 :(得分:2)

您需要设置模型文件的要求。

let { model, id } = req.params;
var Model = require('../models/' + model);
Model.deleteOne({ _id: id })....

希望这对您有所帮助。