node.js - Mongoose 围绕 Min 和 Max 与 Number 的行为

标签 node.js mongoose

我有一个像这样的 Mongoose 方案......

lightbox_opacity:{type:Number, min:0, max:1}

我有两个问题...

  1. 当我尝试插入一个字符串“abc”时,它悄悄地忽略了这个字段插入。架构中的其余字段已成功插入。我的印象是它会抛出异常。有可能吗?

  2. 如果我尝试插入 5,它只是允许它并且似乎最小值和最大值根本没有发挥作用。

我错过了什么?

最佳答案

validation可以帮助你。一个例子如下。

var min = [0, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
var max = [1, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
var numberschema = new mongoose.Schema({
    n: {type: Number, min: min, max: max}
 });

var numberschema = mongoose.model('number', numberschema, 'number');

var insertDocuments = function(db) { 
    var a = new numberschema({
        n: 5
    });

    console.log(a);       

    a.validate(function(err) {
        if (err)
            console.log(err);
    });
    a.save(function (err, ack) {
        if (err) {
            console.log('Mongoose save error : ' + err);
        } else { 
            console.log('Mongoose save successfully...'); 
        }
    }); 
};

当尝试插入5时,出现如下错误

{ [ValidationError: Validation failed]
  message: 'Validation failed',
  name: 'ValidationError',
  errors:
   { n:
      { [ValidatorError: The value of path `n` (5) exceeds the limit (1).]
        message: 'The value of path `n` (5) exceeds the limit (1).',
        name: 'ValidatorError',
        path: 'n',
        type: 'max',
        value: 5 } } }
Mongoose save error : ValidationError: The value of path `n` (5) exceeds the lim
it (1).

当尝试插入abc时,出现如下错误

Mongoose save error : CastError: Cast to number failed for value "abc" at path "
n"

关于node.js - Mongoose 围绕 Min 和 Max 与 Number 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34892143/

相关文章:

javascript - 嵌套 for 循环功能

node.js - 部署Meteor时的环境变量

node.js - 当我尝试初始化 Firebase 应用程序时,为什么 Google Cloud Functions 会抛出 "Invalid value for config firebase.databaseURL"错误?

javascript - MongooseJS 在进行任何验证之前清理字符串

node.js - 使用 mongoose,express 搜索短语

javascript - MongoDB,从数组中删除对象

node.js - Google API NodeJS 库 OAuth2 请求

javascript - 使用 contextify 从 Node vm 内部返回异步结果

javascript - postman 没有收到 POST 的回复

javascript - 如何与node.js同时支持api和web界面数据交互?