MongoDB have an integer always be positive
Asked Answered
B

2

7

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.

Beverly answered 22/4, 2016 at 1:20 Comment(3)
MongoDB doesn't have any schema to restrict. Are you using NodeJS ? If so mongoose will do that.Tinder
@SivaSankar Nope, Im using ReactiveMongo with a Play 2.3 serverBeverly
In regards to $inc, see also #14463689Rifle
P
2

You can't restrict the data input/output on MongoDB, You need to do this in your program/code

Popover answered 22/4, 2016 at 1:47 Comment(1)
From 3.2 version, you have Document Validation that provides the capability to validate documents during updates and insertions.Melly
D
0

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'
  }
)
Delmadelmar answered 12/9 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.