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: ["[email protected]", ""]
    //or email: ["[email protected]", 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" : [ 
        "[email protected]", 
        ""
    ],

store only the proper email:

"email" : [ 
        "[email protected]", 
    ],

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. "[email protected]" in this case while ignoring the null or empty value.)?

4 Answers 4

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 🙏.

Sign up to request clarification or add additional context in comments.

2 Comments

Why not just this.email = this.email ? this.email : undefined;
This is wrong. Using mongoose 4.x, I was able to insert a null value, even with a field marked required: true
0

You can do the following to achieve what you want.

var arr = ['[email protected]', '']; // 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.

Comments

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.

Comments

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
     }]
})

1 Comment

TypeError: Invalid value for schema path default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.