DD DD
DD DD

Reputation: 1238

How to not pass the value by function when using mongoose

There is an api as below.
try catch is omitted here.

exports.test = async(req,res) => {
    const {clientId} = req.body;

  // There is a function that makes an object to use repeatedly.
  function errorReason(arg1) {
    const errorLogs = new ErrorLogs({
      clientId,
      reason: arg1,
    });
    return errorLogs;
  }

  errorReason("server error").save();

And this is the type of clientId.

clientId: mongoose.Schema.Types.ObjectId

When I can pass obejctId or empty String for clientId as request.body.
But when I send empty string, it occurs an error.

validation failed: clientId: Cast to ObjectID failed for value \"\" at path \"clientId\"

How can I make correct function of errorReason? I don't want to save "null" or "empty string" for clientId, even though clientId is empty string.
I hope there isn't clientId for 'new ErrorLogs', when clientId is empty string.

  function errorReason(arg1) {
    const errorLogs = new ErrorLogs({
      reason: arg1,
    });
    return errorLogs;
  }

Thank you so much for reading it.

Upvotes: 0

Views: 62

Answers (2)

Emmanuel
Emmanuel

Reputation: 10900

You can achieve this by making the required field in your schema consume a function. This function decides whether the field is required depending on the type. This will allow you to save an empty string. If you want to save an empty string:

to save an empty string:

const mongoose = require('mongoose');

const errorSchema = new mongoose.Schema({
    clientId: {
        type: mongoose.Schema.Types.ObjectId,
        required: function(){
            return typeof this.clientId === 'string' ? false : true
        },
    }
});


const Errors = mongoose.model('errors', errorSchema)

Update: Seems I misunderstood your intention. If you just want to not set the field clientId in the document, pass undefined to the Schema when you have an empty string. Mongoose will not save the field (unless you have it required, in which case mongoose will throw an error)

exclude empty string field from saved document:

function errorReason(arg1) {
  const errorLogs = new ErrorLogs({
    clientId: clientId || undefined, // handles '', undefined, null, NaN etc
    reason: arg1,
  });
  return errorLogs;
}

errorReason("server error").save();

Upvotes: 1

laxman
laxman

Reputation: 1348

You should use code like bellow.

exports.test = async(req,res) => {
const {clientId} = req.body;

// There is a function that makes an object to use repeatedly.
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
    clientId : clientId, // add here clientId for asign clientId to field
    reason: arg1,
});
return errorLogs;
}

if(!!clientId){ //Here !! means not equal to blank,null,undefine and 0
    errorReason("server error").save();
}

Upvotes: 0

Related Questions