【问题标题】:Mongoose : custom schema typeMongoose:自定义模式类型
【发布时间】: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;

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案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 }
    });
    

    【讨论】:

    • 谢谢你的回答,但我得到另一个错误,如果你想看看,我编辑了我的问题
    • 在类型定义中,您在箭头函数中使用this - 它不会起作用,因为箭头函数保留上下文。将let STRING_LARGE = (key, options) => {...} 更改为function STRING_LARGE (key, options) {...} - 应该没问题。
    • 似乎有效!谢谢!我在使用箭头函数时应该更加小心!
    猜你喜欢
    • 2016-10-31
    • 2014-08-20
    • 2012-12-22
    • 2020-05-24
    • 2013-09-22
    • 1970-01-01
    • 2019-03-18
    • 2014-11-04
    • 1970-01-01
    相关资源
    最近更新 更多