Rahul Ganguly
Rahul Ganguly

Reputation: 2106

mongoose duplicate items getting inserted using $addToSet and $each to push items into the array

I am trying to push an array of objects into a document. I am using $addToSet to try and not insert duplicate data. I want to do a check on applied.studentId. But if I pass the same request twice, then the data is getting inserted. Is there any check on $addToSet and $each that I have to use?

My schema is as follows

 jobId: { type: Number},
 hiringCompanyId: String,
 applied: [{
        studentId: String,
        firstName:String,
        lastName:String,
        gender:String,
        identityType:String,
        identityValue:String,
        email:String,
        phone:String,
    }],

My node code is as follows.

public ApplyForJob(data: JobDto): Promise<{ status: string }> {

    let students = data.applied;


    let findQuery = {hiringCompanyId: data.hiringCompanyId, jobId: data.companyJobId};
    let appliedQuery = {};
    if (!isNullOrUndefined(data.applied.length)) {
        appliedQuery = {
            "$addToSet": {
                "applied": {
                    "$each": data.applied
                }
            }
        };
    }

    return new Promise((resolve, reject) => {
        Jobs.findOneAndUpdate(findQuery, appliedQuery).exec((err, info) => {
            if (err) {
                reject(new UpdateError('Jobs - Update()', err, Jobs.collection.collectionName));
            } else {
                console.log(info);
                resolve({status: "Success"});
            }
        })
    });

}

Upvotes: 0

Views: 1037

Answers (2)

Dmitry Shvetsov
Dmitry Shvetsov

Reputation: 803

as Rahul Ganguly mention absolutely correctly, we cannot use reliably $addToSet with JS objects.

One options is to move applied in to separate collection and make Job schema to ref new Applied model.

Example:

{
  jobId: { type: Number },
  hiringCompanyId: String,
  applied: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Applied'
  }]
}

Upvotes: 0

Rahul Ganguly
Rahul Ganguly

Reputation: 2106

On disabling the date field, $addToSet does not add duplicate values. As per the doc https://docs.mongodb.com/manual/reference/operator/update/addToSet/

As such, field order matters and you cannot specify that MongoDB compare only a subset of the fields in the document to determine whether the document is a duplicate of an existing array element.

Upvotes: 1

Related Questions