Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not allow null in Mongodb

I am using mongoose. I want to create a field with not null as sql does means when a null value try to insert in a collection, it shouldn't allow to store null value.

like image 369
niren Avatar asked Apr 30 '26 03:04

niren


2 Answers

You can use Mogoose validators to validate your model before saving it. There is no way for doing it at mongodb level. MongoDB is a NoSQL, schemaless database.

The required option might be useful

SchemaName = mongoose.Schema(
fieldName: {type: type, required: true}
)
like image 187
Sleiman Jneidi Avatar answered May 01 '26 16:05

Sleiman Jneidi


const mongoose = require('mongoose');

const Schemaname = new mongoose.Schema({
field1: {
        type: String,
        required: true
    },
field2: {
        type: Number,
        required: true
    }
});

module.exports = mongoose.model("Schemanames",Schemaname);