Minimum and maximum number validation in mongoose
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);
}
}
);
});
node.js angular mongodb mongoose mean-stack
|
show 3 more comments
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);
}
}
);
});
node.js angular mongodb mongoose mean-stack
1
You still need to supply adefault
. That is what I presume you mean. "Validation" only means it checks any values you 'actually supply', not those that were never passed in anyway.
– Neil Lunn
Nov 21 '18 at 9:26
I want to restrict values less than 0 and values higher than 1000
– RMD
Nov 21 '18 at 9:27
Yes I understand that, but you seem to not be understanding me. You expect the value to be stored as0
even if yourreq.body
content does not even have a value for that field right? Validation does not do that. That is whatdefault
does. You need BOTH.
– Neil Lunn
Nov 21 '18 at 9:29
If that field is empty it should not store a default value. eg: If I enter -1 it should not save anything.
– RMD
Nov 21 '18 at 9:32
And by saying it does not work you mean what exactly?
– Molda
Nov 21 '18 at 9:37
|
show 3 more comments
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);
}
}
);
});
node.js angular mongodb mongoose mean-stack
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);
}
}
);
});
node.js angular mongodb mongoose mean-stack
node.js angular mongodb mongoose mean-stack
edited Nov 21 '18 at 9:41
RMD
asked Nov 21 '18 at 9:24
RMDRMD
638
638
1
You still need to supply adefault
. That is what I presume you mean. "Validation" only means it checks any values you 'actually supply', not those that were never passed in anyway.
– Neil Lunn
Nov 21 '18 at 9:26
I want to restrict values less than 0 and values higher than 1000
– RMD
Nov 21 '18 at 9:27
Yes I understand that, but you seem to not be understanding me. You expect the value to be stored as0
even if yourreq.body
content does not even have a value for that field right? Validation does not do that. That is whatdefault
does. You need BOTH.
– Neil Lunn
Nov 21 '18 at 9:29
If that field is empty it should not store a default value. eg: If I enter -1 it should not save anything.
– RMD
Nov 21 '18 at 9:32
And by saying it does not work you mean what exactly?
– Molda
Nov 21 '18 at 9:37
|
show 3 more comments
1
You still need to supply adefault
. That is what I presume you mean. "Validation" only means it checks any values you 'actually supply', not those that were never passed in anyway.
– Neil Lunn
Nov 21 '18 at 9:26
I want to restrict values less than 0 and values higher than 1000
– RMD
Nov 21 '18 at 9:27
Yes I understand that, but you seem to not be understanding me. You expect the value to be stored as0
even if yourreq.body
content does not even have a value for that field right? Validation does not do that. That is whatdefault
does. You need BOTH.
– Neil Lunn
Nov 21 '18 at 9:29
If that field is empty it should not store a default value. eg: If I enter -1 it should not save anything.
– RMD
Nov 21 '18 at 9:32
And by saying it does not work you mean what exactly?
– Molda
Nov 21 '18 at 9:37
1
1
You still need to supply a
default
. That is what I presume you mean. "Validation" only means it checks any values you 'actually supply', not those that were never passed in anyway.– Neil Lunn
Nov 21 '18 at 9:26
You still need to supply a
default
. That is what I presume you mean. "Validation" only means it checks any values you 'actually supply', not those that were never passed in anyway.– Neil Lunn
Nov 21 '18 at 9:26
I want to restrict values less than 0 and values higher than 1000
– RMD
Nov 21 '18 at 9:27
I want to restrict values less than 0 and values higher than 1000
– RMD
Nov 21 '18 at 9:27
Yes I understand that, but you seem to not be understanding me. You expect the value to be stored as
0
even if your req.body
content does not even have a value for that field right? Validation does not do that. That is what default
does. You need BOTH.– Neil Lunn
Nov 21 '18 at 9:29
Yes I understand that, but you seem to not be understanding me. You expect the value to be stored as
0
even if your req.body
content does not even have a value for that field right? Validation does not do that. That is what default
does. You need BOTH.– Neil Lunn
Nov 21 '18 at 9:29
If that field is empty it should not store a default value. eg: If I enter -1 it should not save anything.
– RMD
Nov 21 '18 at 9:32
If that field is empty it should not store a default value. eg: If I enter -1 it should not save anything.
– RMD
Nov 21 '18 at 9:32
And by saying it does not work you mean what exactly?
– Molda
Nov 21 '18 at 9:37
And by saying it does not work you mean what exactly?
– Molda
Nov 21 '18 at 9:37
|
show 3 more comments
1 Answer
1
active
oldest
votes
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!
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408836%2fminimum-and-maximum-number-validation-in-mongoose%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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!
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
add a comment |
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!
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
add a comment |
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!
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!
answered Nov 21 '18 at 9:59
Neil LunnNeil Lunn
100k23177187
100k23177187
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
add a comment |
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
Thanks. Well explained.
– RMD
Nov 21 '18 at 10:06
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408836%2fminimum-and-maximum-number-validation-in-mongoose%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You still need to supply a
default
. That is what I presume you mean. "Validation" only means it checks any values you 'actually supply', not those that were never passed in anyway.– Neil Lunn
Nov 21 '18 at 9:26
I want to restrict values less than 0 and values higher than 1000
– RMD
Nov 21 '18 at 9:27
Yes I understand that, but you seem to not be understanding me. You expect the value to be stored as
0
even if yourreq.body
content does not even have a value for that field right? Validation does not do that. That is whatdefault
does. You need BOTH.– Neil Lunn
Nov 21 '18 at 9:29
If that field is empty it should not store a default value. eg: If I enter -1 it should not save anything.
– RMD
Nov 21 '18 at 9:32
And by saying it does not work you mean what exactly?
– Molda
Nov 21 '18 at 9:37