【发布时间】:2018-12-11 01:31:58
【问题描述】:
我在自定义模式类型上遵循了这个mongoose documentation,创建了一个“大字符串”:
"use strict";
const mongoose = require('mongoose')
let STRING_LARGE = (key, options) => {
mongoose.SchemaType.call(this, key, options, 'STRING_LARGE');
};
STRING_LARGE.prototype = Object.create(mongoose.SchemaType.prototype);
STRING_LARGE.prototype.cast = function(val) {
let _val = String(val);
if(!/^[a-zA-Z0-9]{0,400}$/.test(_val)){
throw new Error('STRING_LARGE: ' + val + ' is not a valid STRING_LARGE');
}
return _val; };
module.exports = STRING_LARGE;
我在架构中这样使用它:
"use strict";
const mongoose = require('mongoose');
mongoose.Schema.Types.STRING_LARGE = require('./types/string_large')
const schema = new mongoose.Schema({
details: { type: STRING_LARGE, required: true },
link: { type: STRING_LARGE, required: true }
});
module.exports = schema;
但我得到了错误:
[路径]\schemas[shema.js]:8
详细信息:{ 类型:STRING_LARGE,必需:true },ReferenceError: STRING_LARGE 未定义 在对象。 ([路径]\模式[shema.js]:8:24) ...
-------------- 更新:工作代码 -------------- ------------
使用“函数()”而不是“()=>”
"use strict";
const mongoose = require('mongoose')
function STRING_LARGE (key, options) {
mongoose.SchemaType.call(this, key, options, 'STRING_LARGE');
};
STRING_LARGE.prototype = Object.create(mongoose.SchemaType.prototype);
STRING_LARGE.prototype.cast = function(val) {
let _val = String(val);
if(!/^[a-zA-Z0-9]{0,400}$/.test(_val)){
throw new Error('STRING_LARGE: ' + val + ' is not a valid STRING_LARGE');
}
return _val; };
使用“mongoose.Schema.Types.LARGE_STRING”而不是“LARGE_STRING”
module.exports = STRING_LARGE;
"use strict";
const mongoose = require('mongoose');
mongoose.Schema.Types.STRING_LARGE = require('./types/string_large')
const schema = new mongoose.Schema({
details: { type: mongoose.Schema.Types.STRING_LARGE, required: true },
link: { type: mongoose.Schema.Types.STRING_LARGE, required: true }
});
module.exports = schema;
【问题讨论】: