猫鼬的最小和最大数量验证

时间:2018-11-21 09:24:03

标签: node.js angular mongodb mongoose mean-stack

我正在使用带有Angular 6的MEAN堆栈来实现Web应用程序。我想在那里找到并保存'eValue'。最小值为0,最大值为1000。为此,我在架构中将最小值设置为0,最大值设置为1000。但是,当我输入-1并单击“保存”按钮时,它将-1保存在mongo db中。我想要的是,如果输入的值小于0,则不应在数据库中保存任何内容。这是我的架构。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// Schema for extruded height panel
var eValueSchema = new mongoose.Schema({
    userName: {
        type: String
    },
    eValue: {
        type: Number,
        min: 0,


    }, 
});

module.exports = mongoose.model('eValue', eValueSchema);

这是我的发帖路线

var eValue= require('../../../models/mongoModels/eValue');

router.post("/save", function (req, res) {
    var mod = new eValue(req.body);
    eValue.findOneAndUpdate(
        {
            userName: req.body.userName,
        },

        req.body,
        { upsert: true, new: true },

        function (err, data) {
            if (err) {
                console.log(err);
                res.send(err);
            } else {

                res.send(mod);
            }
        }
    );
});

1 个答案:

答案 0 :(得分:1)

由于您使用的是findOneAndUpdate(),因此默认情况下不会运行验证程序或默认值。

您需要将选项以及newupsert添加到方法中:

 {
    upsert: true,
    new: true,
    runValidators: true,
    setDefaultsOnInsert: true
  }

演示:

const { Schema } = mongoose = require('mongoose');

const uri = 'mongodb://localhost:27017/test';
const opts = { useNewUrlParser: true };

// sensible defaults
mongoose.set('debug', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);

// Schema defs

const testSchema = new Schema({
  name: String,
  value: { type: Number, min: 0, max: 1000, default: 0 }
});

const Test = mongoose.model('Test', testSchema);

// log helper

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {

    const conn = await mongoose.connect(uri, opts);

    // Clean models
    await Promise.all(
      Object.entries(conn.models).map(([k,m]) => m.deleteMany())
    )

    // Do something

    // Set validators and defaults
    let result1 = await Test.findOneAndUpdate(
      { name: 'Bill' },
      { name: 'Bill' },
      {
        upsert: true,
        new: true,
        runValidators: true,
        setDefaultsOnInsert: true
      }
    );
    log(result1);

    // No validator and no default
    let result2 = await Test.findOneAndUpdate(
      { name: 'Ted' },
      { name: 'Ted' },
      {
        upsert: true,
        new: true,
      }
    );
    log(result2);

    // Expect to fail
    try {
      let result3 = await Test.findOneAndUpdate(
        { name: 'Gary' },
        { name: 'Gary', value: -1 },
        {
          upsert: true,
          new: true,
          runValidators: true,
          setDefaultsOnInsert: true
        }
      );
      log(result3);
    } catch(e) {
      console.error(e)
    }

    console.log('Tests done!');


  } catch(e) {
    console.error(e)
  } finally {
    mongoose.disconnect()
  }

})()

我们希望这是第一个操作的工作属性,但是第二个操作实际上不会插入默认值。请注意,猫鼬文档结果的“日志”实际上显示了0,即使您可以看到它未持久存储在数据库中。

对于最后一个示例,我们打开验证器并得到预期的验证错误。删除该选项将不会引发任何错误。

示例输出:

Mongoose: tests.deleteMany({}, {})
Mongoose: tests.findOneAndUpdate({ name: 'Bill' }, { '$setOnInsert': { __v: 0, value: 0, _id: ObjectId("5bf52c1b9d265f1507f94056") }, '$set': { name: 'Bill' } }, { upsert: true, runValidators: true, setDefaultsOnInsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "value": 0,
  "_id": "5bf52c1b9d265f1507f94056",
  "name": "Bill",
  "__v": 0
}
Mongoose: tests.findOneAndUpdate({ name: 'Ted' }, { '$setOnInsert': { __v: 0 }, '$set': { name: 'Ted' } }, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "value": 0,
  "_id": "5bf52c1b97f623c9da4341a0",
  "name": "Ted",
  "__v": 0
}
{ ValidationError: Validation failed: value: Path `value` (-1) is less than minimum allowed value (0).
    ... rest of stack ...
    at ValidationError.inspect     at formatValue (util.js:561:31)
    at inspect (util.js:371:10)
    at Object.formatWithOptions (util.js:225:12)
    at Console.(anonymous function) (console.js:193:15)
    at Console.warn (console.js:210:31)
    at /home/neillunn/working/minmax/index.js:75:15
    at process._tickCallback (internal/process/next_tick.js:68:7)
  errors:
   { value:
      { ValidatorError: Path `value` (-1) is less than minimum allowed value (0).
          at new ValidatorError         message: 'Path `value` (-1) is less than minimum allowed value (0).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'min',
        path: 'value',
        value: -1,
        reason: undefined,
        [Symbol(mongoose:validatorError)]: true } },
  _message: 'Validation failed',
  name: 'ValidationError' }
Tests done!