我在自定义架构类型上遵循了此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 在对象。 ([路径] \ schemas [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;
答案 0 :(得分:1)
您正在将类型分配给mongoose.Schema.Types.STRING_LARGE
,然后使用STRING_LARGE
-在此处抛出ReferenceError
。您必须直接使用您的类型:
const schema = new mongoose.Schema({
details: { type: mongoose.Schema.Types.STRING_LARGE, required: true },
link: { type: mongoose.Schema.Types.STRING_LARGE, required: true }
});