0

I have tried to add a default trim validation to array but I don't understand why it is not working out. should Iterate elements in array to add trim or will it apply to each element in collection? I trim the below code assuming that trim will work for array elements but it is not. Can some please tell me why this is happening.

model.js

const mongoose = require("mongoose");
const schema = mongoose.Schema;
const toDoSchema = new schema({
    title:{
        type: String,
        require: [true, "title is required"],
        trim: true
        },
    tasks:{
        type:[String],
        trim: true
        }
    });
const toDoModel = mongoose.model("toDo", toDoSchema);
module.exports = toDoModel;

controller.js

//importing model
const toDoModel = require('../models/ToDoModel');

//creating controller function
const createToDoController = async (req,res)=>{
    try{
    const {title,tasks} = req.body;

    if(!title) //input validation
    { 
        throw new Error("Please provide the title");
    }
    const newToDo = await toDoModel.create({ title, tasks });
    res.status(201).json({
        success: true,
        message: "User Created Successfully",
        newToDo,
      });
    }
    catch(err){
        res.status(500).json({
            success: false,
            message: "Unable to perform create operation",
            error: err
        })
        res.send(err.message);
    } 

}
module.exports = createToDoController;

postman output: enter image description here

Indratej Reddy
  • 165
  • 1
  • 7

1 Answers1

0

Solution:

const mongoose = require("mongoose");
const schema = mongoose.Schema;
const toDoSchema = new schema({
    title:{
        type: String,
        require: [true, "title is required"],
        trim: true
        },
    tasks:[{   type: String,   trim: true }]

    });
const toDoModel = mongoose.model("toDo", toDoSchema);
module.exports = toDoModel;

Credits and special thanks to @Marc

Indratej Reddy
  • 165
  • 1
  • 7