0

I have the following schema:

const userSchema = new mongoose.Schema({
    email: [{
        type: String,
        trim: true,
     }]
})

When saving a new user,

const user = new User({
    email: ["example@example.com", ""]
    //or email: ["example@example.com", null]
})

try{
   await user.save()
} catch (e) {
   console.log(e)
}

This will save both those values (including empty string and null respectively).

Is there a way to save only the proper email value while discarding the empty or null value. Instead of this:

"email" : [ 
        "example@example.com", 
        ""
    ],

store only the proper email:

"email" : [ 
        "example@example.com", 
    ],

Currently for other schema fields I am using set. For example, in the user schema above

url: {
    type: String,
    set: deleteEmpty
}



const deleteEmpty = (v) => {
  if(!v) {
      return undefined
  }

  return v
}

This will of course not save the url field at all if the value is empty or null. Using this method on the email field above however will generate a null value.

Is there a way to store only the proper email value (i.e. "example@example.com" in this case while ignoring the null or empty value.)?

4 Answers4

2

I think you can make it something like this code below with your userSchema:

userSchema.pre('save', function(next) {
  this.email = this.email.filter(email => email);
  next();
})

The code above ☝️ will igrone all empty or null value in an array. You can try it.

Or the Second Options, you can add required on your email field in your userSchema. It's well looks like this code below:

const userSchema = new mongoose.Schema({
  email: [{
      type: String,
      trim: true,
      required: true // add some required
   }],
});

The code above ☝️, will give you an error if you passing an empty string on your array.

I hope it's can help you .

Mohammed Amir Ansari
  • 2,311
  • 2
  • 12
  • 26
Titus Sutio Fanpula
  • 3,467
  • 4
  • 14
  • 33
0

You can do the following to achieve what you want.

var arr = ['example@example.com', '']; // variable to keep the an array containing values

var i;
for (i = 0; i < arr.length; i++) {
  if (arr[i] == null || arr[i] == '') {
    arr.slice(i); // remove null or '' value
  }
}

console.log('normalized array: ', arr);
// schema code
const user = new User({
    email: arr
})

try{
   await user.save()
} catch (e) {
   console.log(e)
}

Good luck, I hope I answered your question.

James Mwase
  • 828
  • 1
  • 16
  • 29
0

If anyone has one or more fields that takes array value and wants to check for each field, I recommend using a middleware on the pre save hook.

supplierSchema.pre('save', normalizeArray)


const normalizeArrray = function(next) {

    //take the list of object feilds and for each field check if it is array
    Object.keys(this.toObject()).forEach((field) => {

        if(Array.isArray(this[field])) {

            //removes null or empty values
            this[field] = this[field].filter(field => field)
        }
    })

    next()
}

This just builds on the answer already approved above.

0

Simply set the default value of the field you wish to ignore, if empty, to undefined. Also, set required to false.

Use the code below:

const userSchema = new mongoose.Schema({
    email: [{
        type: String,
        trim: true,
        required: false,
        default: undefined
     }]
})