Reputation: 311
I am implementing a web application using MEAN stack with Angular 6. There I want to find and save 'eValue's. There the minimum value is 0 and the max value is 1000. For that, I set the min value to 0 and max value to 1000 in the schema. But when I enter -1 and click 'save' button it saves -1 in mongo db. What I want is if I enter values less than 0, it should not save anything in database. Here is my schema.
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);
This is my post route
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);
}
}
);
});
Upvotes: 2
Views: 9872
Reputation: 151132
Because you are using findOneAndUpdate()
and this does not run validators or defaults by default.
You need to add the options to the method, along with the new
and upsert
:
{
upsert: true,
new: true,
runValidators: true,
setDefaultsOnInsert: true
}
To demonstrate:
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()
}
})()
This we expect to work property for the first action, but the second action will not actually insert the default value. Note that the "log" of the Mongoose Document result actually shows the 0
even though you can see this was not persisted to the database.
For the final example we turn the validators on and get the expected validation error. Removing the option would result in no error being thrown.
Sample output:
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!
Upvotes: 7