skip to Main Content

I am using MERN stack to develop web application. I created a controller to create a document namely "UserServiceProfile" with a nested array of "serviceCategory" documents in it. However, after creating the first document of UserServiceProfile, subsequence creation throws "duplicate error" with the following message:

 {
    "msg": "Duplicate value found for .n        Please choose another value.n        "
}

The embedding document schema is:

 const UserServiceProfileSchema = new mongoose.Schema({
    accountType: {
        type: String,
        enum: {
            values: ['service man', 'service consumer', 'business'],
            message: '{VALUE} is not supported'
        },
        default: 'service consumer'
    },
    services: {
        type: [ServiceCategorySchema],
        message: 'Service is not supported'
    },
    user: {
        type: mongoose.Types.ObjectId,
        required: [true, 'Please provide user'],
        ref: 'User'
    }, 
})

const UserProfileModel = mongoose.model('profile', UserProfileSchema)
const UserServiceProfileModel = mongoose.model('userServiceProfile', UserServiceProfileSchema)

The embedded document schema:

const ServiceCategorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please provide service name'],
        minlength: 3,
        maxlength: 30,
    },
    description: {
        type: String,
        minlength: 10,
        maxlength: 200,
        required: [true, 'Please provide service description']
    },
    active: {
        type: Boolean,
        default: true
    }
})

const ServiceCategoryModel = mongoose.model('serviceCategory', ServiceCategorySchema)

The controller where the document is created is:

const createUserServiceProfile = async(req, res) =>{ 
    const {accountType, service} = req.body
    const {userID} = req.user

    if( !accountType){
        throw new BadRequestError('Please provide account type')
    }
    if(!service){
        throw new BadRequestError('Please provide service')
    }

    // check if service profile exist
    const existingServiceProfile = await UserServiceProfileModel.findOne({user: userID})
    
    if(existingServiceProfile){
        throw new BadRequestError("Profile created already")
    }
    console.log(userID)
    const user = await UserModel.findOne({_id: userID})
    if(!user){
        throw new UnAuthenticatedError(`User with ID ${userID} not found`)
    }

    const newService = {
        name: service.name,
        _id: service._id,
        description: service.description,
        active: service.active
    }

    const userServiceProfile = await UserServiceProfileModel.create(
            {
                accountType, 
                services: [newService], 
                user: userID
            }
        )

    res.status(StatusCodes.CREATED).json(
        {
            success: true, 
            msg: 'User service profile created', 
            userServiceProfile
        }
    )
}

Thank you as you take your precious time to assist.

2

Answers


  1. You are recreating a service with the same _id, try to store it as an array of references:

    const UserServiceProfileSchema = new mongoose.Schema({
      ...
      services: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'serviceCategory',
        message: 'Service is not supported',
      }],
      user: {
        type: mongoose.Schema.Types.ObjectId,
        required: [true, 'Please provide user'],
        ref: 'User',
      },
    });
    

    And save it with:

    const createUserServiceProfile = async (req, res) => {
        const { accountType, service } = req.body;
        const { userID } = req.user;
      
        if (!accountType) {
          throw new BadRequestError('Please provide account type');
        }
        if (!service) {
          throw new BadRequestError('Please provide service');
        }
      
        // check if service profile exist
        const existingServiceProfile = await UserServiceProfileModel.findOne({
          user: userID,
        });
      
        if (existingServiceProfile) {
          throw new BadRequestError('Profile created already');
        }
        console.log(userID);
        const user = await UserModel.findOne({ _id: userID });
        if (!user) {
          throw new UnAuthenticatedError(`User with ID ${userID} not found`);
        }
      
        const userServiceProfile = await UserServiceProfileModel.create({
          accountType,
          services: [service._id],
          user: userID,
        });
      
        res.status(StatusCodes.CREATED).json({
          success: true,
          msg: 'User service profile created',
          userServiceProfile,
        });
      };
    
    Login or Signup to reply.
  2. Although you removed the unique index from code, it still exists in the collection itself. You should remove the unique index from the collection.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search