gpt4 book ai didi

node.js - Mongoose - 如何为所有模型创建通用方法?

转载 作者:搜寻专家 更新时间:2023-10-31 23:47:54 26 4
gpt4 key购买 nike

我有一个需要为所有模型实现的通用方法。现在我对每个模型都这样做:

var Product = module.exports = mongoose.model('Product', ProductSchema);

module.exports.flush = function (filename, cb) {
"use strict";

var collection = require(filename);

// todo: reimplement with promises
this.remove({}, function (err) {
if (err) {
console.log(err);
}
else {
this.create(collection, cb);
}
}.bind(this));
};

我怎样才能一次添加这个方法,以便它存在于所有模型中?

最佳答案

只需为 Model 定义函数:

var mongoose = require('mongoose');
mongoose.Model.flush = function (filename, cb) {
"use strict";

var collection = require(filename);

// todo: reimplement with promises
this.remove({}, function (err) {
if (err) {
console.log(err);
}
else {
this.create(collection, cb);
}
}.bind(this));
};

那么你创建的所有模型都会继承flush函数:

var Product = module.exports = mongoose.model('Product', ProductSchema);
Product.flush();

关于node.js - Mongoose - 如何为所有模型创建通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com