Mongoose:在一个集合下动态加载不同的模式

Mongoose : Dynamically load different schema under one collection

本文关键字:加载 动态 模式 集合 一个 Mongoose      更新时间:2023-09-26

我使用的是nodejs,并且有一个注册页面,该页面有一个select标记,可以在Client和Employee之间进行选择。

我想要一个模型和两个模式:-用户:将包含公共道具,例如:邮件,姓名,通行证。。。-EmployeeSchemma,具有员工的特定文件-ClientSchemma,其中包含客户端的特定字段。

这就是In想要在我的服务器端实现的:

var User=require("models/user");
router.post("/register",function(req,res){
var newUser=new User();
if(req.body.type=="client")
   //  make the newUser use the ClientSchema //
if(req.body.type=="employee")
  //   the newUser instance will use the EmployeeSchema //
});

请问我怎样才能达到这样的结果(?)注意,我只想使用一个模型,它可以根据表单中的用户选择对客户和员工用户进行建模。

如果你想要一个"动态模型",我想你正在寻找猫鼬中严格为false的设置

正如您所知,默认情况下,Mongoose将遵循您设置的模式/模型,设置strict:false将允许您保存不在模式/模型中的字段。

因此,对于您的情况,在您的文件模型/用户中,您将希望在创建模式时包含"strict:false"作为第二个参数:

var userSchema = new Schema({
    email: String,
    name: String,
    password: String
    // other parts of your user schema
}, {strict: false})

现在,您应该能够在同一集合中相应地设置客户和员工字段。