简体   繁体   English

从猫鼬模式调用自定义方法

[英]Calling custom method from mongoose schema

I made custom methods with two ways, But not working. 我用两种方法制作了自定义方法,但是没有用。

models 楷模

...
// I read it from other stack overflow QA
categorySchema.methods.postChange = function(){
console.log('postChange');
};

// Mongoose reference doc
categorySchema.methods('postChange', function(){
console.log('postChange');
});

var Category = mongoose.model('category',categorySchema);

module.exports = Category;

routes 路线

...
router.post('/update_cat', upload.single('image_file'), function(req, res){
Category.findOneAndUpdate({name: req.body.name}, {href: req.body.href}, function(err, doc){
    doc.href = req.body.href;
    Category.postChange();
    (err)?res.json(err):res.redirect('./reg_line');
    });
});

and The error is 'Category.postChange is not a function'. 错误是“ Category.postChange不是函数”。

It is not advisable to put your function in the models but you should define them in the routes itself. 建议不要将功能放在模型中,但应在路线本身中定义它们。 Models are for your mongoose schema. 模型适用于您的猫鼬模式。 Just in case, you are getting this error because you are not exporting the function. 以防万一,您由于未导出函数而收到此错误。

exports.categorySchema.methods.postChange = function(){
     console.log('postChange');
};

or 要么

exports.categorySchema.methods('postChange', function(){
     console.log('postChange');
});

You can set the function as static with this code : 您可以使用以下代码将功能设置为静态

// Mongoose reference doc
categorySchema.statics.postChange = function(){
    console.log('postChange');
};

module.exports = mongoose.model('category',categorySchema);

Documentation : http://mongoosejs.com/docs/guide.html#statics 文档: http : //mongoosejs.com/docs/guide.html#statics

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM