猫鼬:自定义架构类型

maximeSurmontSO

我遵循了有关自定义架构类型的猫鼬文档,以创建“大字符串”:

"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;

但是我得到了错误:

[path] \ 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;
拉多斯瓦夫·米尔尼克

您正在将您的类型分配给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 }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章