Is it possible to enforce a field and have mongoDB always have a positive value for an integer field? It would be ideal if increment wouldn't make a number negative.
MongoDB have an integer always be positive
You can't restrict the data input/output on MongoDB, You need to do this in your program/code
From 3.2 version, you have Document Validation that provides the capability to validate documents during updates and insertions. –
Melly
As mentioned by thepirat000 you can use document validation. There is an example in step two in the Document validation documentation. But here is an example with some restrictions to limit the size using a model in JS:
const { default: mongoose } = require('mongoose')
courts = [
'Milton',
'Gray',
'Brooke',
'Marlowe',
'Spencer',
'Shelley',
'Pope',
'Byron',
'Coleridge',
'Herrick',
'Dryden',
'Tennyson'
]
const locationSchema = new mongoose.Schema(
{
geo: {
type: {
type: String,
enum: ['Point'],
required: false
},
coordinates: {
type: [Number],
required: false
}
},
court: { type: String, enum: courts },
courtNumber: {
type: Number,
validate: {
validator: (value) => value > 0 && value <= 18,
message: 'Parkleys estate only has 18 max'
}
},
image: { type: String },
issues: [{ type: String }]
},
{
timestamps: true,
collection: 'locations'
}
)
© 2022 - 2024 — McMap. All rights reserved.
$inc
, see also #14463689 – Rifle