如何在mongoose模式中将最小值设置为大于0?

时间:2017-07-11 10:16:50

标签: node.js mongoose

我认为这很简单,但我很困惑。 如何为mongoose>添加最小值? 0?

var customer = new Schema({
      cash: {
        type: Number,
        minimum: 0
      },
      validate: {
        validator: function(value) {
          return value > 0;
        },
        message: 'cash need to be > 0'
      },
});

此代码允许0值,但我想做> 0

我知道,我可以这样做

using Microsoft.Office.Interop.Excel;  

void CreateChart()
{
    ChartData gChartData;
    Workbook gWorkBook;
    Worksheet gWorkSheet;
    //  Create the chart and set a reference to the chart data.
    var myChart = ActivePresentation.Slides[1].Shapes.AddChart() as Microsoft.Office.Interop.PowerPoint.Chart;
    gChartData = myChart.ChartData;
    //  Set the Workbook and Worksheet references.
    gWorkBook = gChartData.Workbook;
    gWorkSheet = gWorkBook.Worksheets[1];
    //  Add the data to the workbook.
    gWorkSheet.ListObjects["Table1"].Resize(gWorkSheet.Range["A1:B5"]);

    gWorkSheet.Range["Table1[[#Headers],[Series 1]]"].Value = "Items";

    gWorkSheet.Range["a2"].Value = "Coffee";
    gWorkSheet.Range["a3"].Value = "Soda";
    gWorkSheet.Range["a4"].Value = "Tea";
    gWorkSheet.Range["a5"].Value = "Water";
    gWorkSheet.Range["b2"].Value = "1000";
    gWorkSheet.Range["b3"].Value = "2500";
    gWorkSheet.Range["b4"].Value = "4000";
    gWorkSheet.Range["b5"].Value = "3000";

    //ToDo: Style
}

*现金是浮动的,可以很小

但它太长了,有更简单的方法吗?

2 个答案:

答案 0 :(得分:0)

http://mongoosejs.com/docs/api.html#schema-number-js

试试这个:

var customer = new Schema({
  cash: {
    type: Number,
    min: 1
  }
});

我假设您使用的是mongoose.js?

答案 1 :(得分:0)

您可以在定义架构时指定最小值。

    var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});
var Breakfast = db.model('Breakfast', breakfastSchema);

`

var badBreakfast = new Breakfast({
  eggs: 2,
  bacon: 0,
  drink: 'Milk'
});
var error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
  'Too few eggs');
assert.ok(!error.errors['bacon']);
assert.equal(error.errors['drink'].message,
  '`Milk` is not a valid enum value for path `drink`.');

badBreakfast.bacon = 5;
badBreakfast.drink = null;

error = badBreakfast.validateSync();
assert.equal(error.errors['drink'].message, 'Path `drink` is required.');

badBreakfast.bacon = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['bacon'].message, 'Why no bacon?');