Search code examples
javascriptmongodbparse-platform

Parse Object Save() Inserting Duplicated Records


I have a Parse application with an insert function which saves an object (Audit) and then child objects (DetailAudit) with a foreach loop on a javascript array.

The problem is that sometimes this function is inserting multiple child records (DetailAudit) in the database.

I tried to query for the existence of the child record before inserting a new record but the save() method is executed before the actual query.

The insert method is this:

function insert(form,handler){
    var audit = new Audit();
        audit.set("type",Type.createWithoutData(form.auditoria));
        audit.set("folio",form.folio.toUpperCase());
        audit.set("start",moment(form.inicio, 'DD/MM/YYYY').toDate());
        audit.set("end",moment(form.fin, 'DD/MM/YYYY').toDate());
        audit.set("objectives",form.objetivos);
        audit.set("goals",form.alcances);
        audit.set("audits",form.auditores);
        audit.set("auditTest",User.createWithoutData(form.auditorTest));
        audit.set("auditLeader",User.createWithoutData(form.auditorLider));
        audit.set("group",form.grupo);
        audit.save().then(function(audit){
                    var procesos = form.tab;

                    procesos.forEach(function(item) {

                        // Here I tried to query for the existence but didn't work

                        var detail = new DetailAudit();
                            detail.set("process",AuditProcess.createWithoutData(item.procesoId));
                            detail.set("clauses",item.clausulas);
                            detail.set("standar",Standar.createWithoutData(item.estandarId));
                            detail.set("area",Area.createWithoutData(item.areaId));
                            detail.set("auditor",User.createWithoutData(item.auditorId));
                            detail.set("method",item.metodologia);
                            detail.set("comment",item.comentario);
                            detail.set("questions",0);
                            detail.set("grade",0);
                            detail.set("comment",item.comentario);
                            detail.set("audit",audit);
                            detail.save({
                                success:function(detail){
                                    var pros =  new ProcessScheme();
                                        pros.set("title","EQUIPO, INSTALACIÓN Y MATERIALES")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();
                                    var pros =  new ProcessScheme();
                                        pros.set("title","ENTRADAS")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();
                                    var pros =  new ProcessScheme();
                                        pros.set("title","SALIDAS")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();
                                    var pros =  new ProcessScheme();
                                        pros.set("title","INFORMACIÓN DOCUMENTADA")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();

                                    var pros =  new ProcessScheme();
                                        pros.set("title","INDICADORES DE DESEMPEÑO")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();
                                    var pros =  new ProcessScheme();
                                        pros.set("title","CONOCIMIENTOS, ENTRENAMIENTO Y HABILIDADES")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();
                                    var pros =  new ProcessScheme();
                                        pros.set("title","ANÁLISIS DE RIESGO")
                                        pros.set("content","....")
                                        pros.set("detail",detail)
                                        pros.save();
                                },
                            });

                        var audits = [];
                            audits.push(User.createWithoutData(item.auditorId))
                            if(audits.length == procesos.length){
                                audit.set("audits",audits);
                                audit.save();
                            }
                    });

                    sendEmail(audit);

                    handler({status:200,msn:"Auditoría creada exitosamente",res:audit});
            }).catch(function(error){
                    handler({status:500,msn:"Error al crear usuario",res:error});
            });
}

As I said, I tried to query the existence of DetailAudit object before is inserted but the query alwasy returns empty results.

This project just got in my hands I am really lost on this parse server subject, any advice would help.


Solution

  • You can create a mongo unique index to ensure uniqueness in your collection. This will prevent duplicate inserts.

    db.collection.createIndex( <key and index type specification>, { unique: true } )
    

    In your case, you could create a unique index on 'Detail Audit' on 'title' and 'audit' to ensure that each audit only has unique titles.

    db.collection.createIndex({'title':1,'_p_audit':1}, { unique: true } )
    

    You can also save multiple objects with Parse by using:

    Parse.Object.saveAll([arrayOfObjects])