如何在路由中传递模式模型

时间:2019-04-11 07:22:45

标签: node.js express mongoose

我已经在控制器文件的函数中定义了模式模型,该模型在MongoDB中创建了一个新集合。我希望模型在路由文件中传递。我曾尝试根据自己的模式进行input_address.isEnabled = false的操作,但在猫鼬的lib /索引文件上却遇到了错误:-const Thing = mongoose.model('admin.companyName');

我在控制器内的功能:-

throw new mongoose.Error.MissingSchemaError(name); MissingSchemaError: Schema hasn't been registered for model "admin.companyName".
Use mongoose.model(name, schema)

如何将var admin.save((err, doc) =>{ if(!err){ res.send(doc); //make copy to Company collection let arr = Object.keys(doc.schema.obj); //doc.schema.paths if I need same ID let Obj = {}; arr.map(key => Obj[key] = doc[key]); var thingSchema = new mongoose.Schema({}, { strict: false, collection: admin.companyName }); var Thing = mongoose.model(admin.companyName , thingSchema); var thing = new Thing(Obj); thing.save(); console.log(thing); 传递到路由文件,以便可以在我的 route 之一中使用:-

注意:- Thing = mongoose.model(admin.companyName , thingSchema);的架构名称不是固定的,并且会不断更改

admin.companyName

编辑:-路由文件

const Thing = mongoose.model('admin.companyName');
Thing.updateOne( { emailResetTokenn: emailTokenn },{ $set: { verified: true }},(err) =>{ ......

1 个答案:

答案 0 :(得分:0)

如果您要查找模型Thing,则可以使用mongoose.modelNames()返回创建的所有模型名称的数组。

const Genre = mongoose.model('Genre', genreSchema);
const Book = mongoose.model('Book', bookSchema);

console.log(mongoose.modelNames()) // gives ['Genre', 'Book']

这只会为您提供模型名称,您需要弄清楚如何使用admin属性找到所需的模型。

修改 如果请求对象中具有Admin属性,则可以在路由处理程序的内部获取您需要的Thing模型:

router.get('/:adminId/verify',function(req,res){
    console.log('request recieved');
    const emailTokenn = req.query.id;
    console.log(emailTokenn);
    Admin.FindOne({_id: req.params.adminId})
       .exec()
       .then(admin => {
          const Thing = mongoose.model(admin.companyName);
          Thing.updateOne( { emailResetTokenn: emailTokenn },{ $set: { verified: true }},(err) =>{})
       })

相关问题