Kraken
Kraken

Reputation: 119

The replacement document must not contain atomic operators

I've this function for save new record or update an existing item:

async function saveEmploy(c){
let employ=new collaboratore();
employ=c;
let docs=c.documenti.length>0?c.documenti:undefined;
if(docs!==undefined){
    let oldDocs=docs.map(d=>{if (d._id) d;});
    oldDocs.forEach(async d=>{
        let oldDoc=await documento.findOneAndReplace({_id:doc._id},doc,{upsert:true});
        employ.documenti.push(oldDoc._id);
    });
    let newDocs=docs.map(d=>{if(!d._id)d;});
    newDocs.forEach(async d=>{
        let newDoc=await d.save();
        employ.documenti.push(newDoc._id);
    });
}

let savedEmploy=null;
if(c._id){
    savedEmploy=await collaboratore.findOneAndReplace({_id:c._id},employ,{new:true,upsert:true});
}
else
    savedEmploy=await employ.save();
console.log('saved');
return savedEmploy;
}

These are the schemas:

const collaboratoreschema =new schema({
   dataregistrazione:{type:Date,default:Date.now},
   nominativo:nominativoschema,
   localitanascita:{type:String,required:true,trim:true},
   provincianascita:{type:String,required:true,trim:true},
   datanascita:{type:Date,required:true},
   indirizzoresidenza:{type:indirizzoEmbeddedSchema,required:true},
   indirizzodomicilio:{type:indirizzoEmbeddedSchema,set:v=>!v || v.length===0?undefined:v},
   telefoni:{type:[telefonoschema],required:true},
   indirizziemail:{type:[require('../email.schema.js')],set:v=>!v || v.length===0?undefined:v},
   codicefiscale:{type:String,required:true,uppercase:true,trim:true,match:/^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$/},
   note:{type:String,trim:true,set:v=>!v || v===''?undefined:v},
   immagine:imageEmbeddedSchema,
   documenti:[{type:schema.Types.ObjectId,ref:'tbFiles'}],
   datainiziorapporto:{type:Date,required:true},
   datafinerapporto:Date,
   riferimentoazienda:{type:schema.Types.ObjectId,ref:'tbFornitori',set:v=>!v || v==={} || v===''?undefined:v},
   attivo:{type:Boolean,default:true}
},{timestamps:true,useNestedStrict: true,collection:'tbCollaboratori'});

When I execute the findOneAndReplace function, I get this error:

The replacement document must not contain atomic operators.

I don't undestand where is my mistake.

Thanks for your help

Upvotes: 2

Views: 2320

Answers (1)

peter
peter

Reputation: 593

I bet your update document, either doc or employ, contains update operations ($set: {...}).
As the name suggests, findOneAndReplace replaces contents of the document, so update operators are not allowed here.
Most probably you need to use findOneAndUpdate here or make sure your update document contains an entire new record.
Refer to this post What's the difference between findOneAndUpdate and findOneAndReplace? and this article MongoDB findOneAndDelete findOneAndUpdate findOneAndReplace for details as well.

Upvotes: 2

Related Questions