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.)?