我有一个猫鼬模型:
const mongoose = require('mongoose');
const id = mongoose.Schema.Types.ObjectId;
const templateSchema = mongoose.Schema({
_id: id,
heading: {
type: String,
required: true
},
content: {
type: String,
required: true
}
});
module.exports = mongoose.model("template", templateSchema);
在我的应用程序中,我具有基于角色的其余API控件。管理员可以创建这些模板,客户端/用户将在前端进一步使用这些模板。但是对于初始化,我需要通过admin在数据库中创建3-4个默认模板。
这些默认模板将在应用程序启动后立即从数据库本身呈现/获取。管理员将使用适当的端点进一步创建更多新模板,这些模板将被推送到默认模板的现有数据中。
我读过有关在猫鼬模型中使用static methods
的信息,但不确定这样做是否正确。
尽管我尝试了以下JS方法,但是没有用。
const mongoose = require("mongoose");
const id = mongoose.Schema.Types.ObjectId;
const templateSchema = mongoose.Schema({
_id: id,
heading: {
type: String,
// required: true,
},
content: {
type: String,
// required: true,
},
});
module.exports = mongoose.model("template", templateSchema);
// let Template = mongoose.model("template", templateSchema);
let defaultTemplates = [
{
heading: "CONNECTION REQUEST",
content:
"<div><p>Dear Mark,</p><p>It was great meeting you at the ESRI conference in San Diego last month.The mapping and charting work you do for airports sound fascinating.I'd definitely like to stay up-to-date with your career.</p><p>Thank you,</p><p>Lindsey</p></div>",
},
{
heading: "MESSAGE AFTER CONNECTION ACCEPTED",
content:
"<div><p>Dear Mark,</p><p>It was great meeting you at the ESRI conference in San Diego last month.The mapping and charting work you do for airports sound fascinating.I'd definitely like to stay up-to-date with your career.</p><p>Thank you,</p><p>Lindsey</p></div>",
},
{
heading: "INTRESTED MESSAGE",
content:
"<div><p>Dear Mark,</p><p>It was great meeting you at the ESRI conference in San Diego last month.The mapping and charting work you do for airports sound fascinating.I'd definitely like to stay up-to-date with your career.</p><p>Thank you,</p><p>Lindsey</p></div>",
},
];
let new_details = [];
defaultTemplates.forEach((temp) => {
temp._id = new mongoose.Types.ObjectId();
new_details.push(temp);
});
templateSchema.statics.saveTemplate = function(new_details, callback){
var template = new this(new_details);
template.save(callback);
};
它不会将模板保存到数据库,并一次又一次出现以下错误:
Template.saveTemplate(function(result) {
^
TypeError: Template.saveTemplate is not a function
请帮助我解决这个问题。