Mongoose: Require Feature information

Created on 12 Jun 2020  路  6Comments  路  Source: Automattic/mongoose

var UserSchema = new mongoose.Schema({
    privilege: {
        type: Number
    },
    savedFormat: {
         type: String,
         required: function() { return this.privilege === 1; },
         default: 'ABDCE'
    }
}, { timestamps: true });

I want to have the savedFormat field only when the privilege is one and if other no savedFormat field should appear. Do mongoose provide some feature where I can retain the default value as well as provide some condition to field.

help

All 6 comments

Can you please clarify your question? I don't quite understand. Your code, as written, should work in terms of making savedFormat required if and only if privilege === 1.

Sir, I have 3 types of privilege 1 , 2 and 3. Only the user with privilege 1 would have savedFormat saved in the mongodb but with the above code all the users have the savedFormat field in the database (with value 'ABCDE').

I need something that when the user privilege is 1, he/she must have the savedFormat otherwise savedFormat field should not be saved in the DB strictly.

Try:

var UserSchema = new mongoose.Schema({
    privilege: {
        type: Number
    },
    savedFormat: {
         type: String,
         required: function() { return this.privilege === 1; },
         default: function() { return this.privilege === 1 ? 'ABDCE' : void 0; }
    }
}, { timestamps: true });

I think @amolsr would want to validate instead. Take a look at custom validators.

9213.js

'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;
const assert = require('assert');

const userSchema = new Schema({
  privilege: {
    type: Number
  },
  savedFormat: {
    type: String,
    required () { return this.privilege === 1; },
    validate: {
      validator  () {
        if (this.privilege !== 1 && this.savedFormat != null) {
          return false;
        }
        return true;
      },
      message: 'Saved format can not be present unless privilege is 1.'
    }
  }
}, { timestamps: true });


const User = mongoose.model('User', userSchema);

const validUser1 = new User({ privilege: 1, savedFormat: 'hello' });
const validUser2 = new User({ privilege: 2 });

const err1 = validUser1.validateSync();
const err2 = validUser2.validateSync();
assert.ok(err1 == null);
assert.ok(err2 == null);

const invalidUser1 = new User({ privilege: 1 });
const invalidUser2 = new User({
  privilege: 2,
  savedFormat: 'Some value that should not be present'
});

const err3 = invalidUser1.validateSync();
const err4 = invalidUser2.validateSync();

assert.equal(err3.errors['savedFormat'].message, 'Path `savedFormat` is required.');
assert.equal(err4.errors['savedFormat'].message, 'Saved format can not be present unless privilege is 1.');

console.log('All assertions passed.');

Output

All assertions passed.

Thank you for the help sir both the solution worked like a charm. 馃榿

Was this page helpful?
0 / 5 - 0 ratings