簡體   English   中英

從貓鼬模式調用自定義方法

[英]Calling custom method from mongoose schema

我用兩種方法制作了自定義方法,但是沒有用。

楷模

...
// 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;

路線

...
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');
    });
});

錯誤是“ Category.postChange不是函數”。

建議不要將功能放在模型中,但應在路線本身中定義它們。 模型適用於您的貓鼬模式。 以防萬一,您由於未導出函數而收到此錯誤。

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

要么

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

您可以使用以下代碼將功能設置為靜態

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM