Home > Blockchain >  Mongoose return null sometime and many time data
Mongoose return null sometime and many time data

Time:09-16

i have created a mongoose schema of contacts where i have created my own defined id my schema is this

const mongooseSchema = new mongoose.Schema({
    _id:{
        type:String,
        unique:true,
        required:true
    },
    firstName:{type:String},
    lastName: {type:String},
    name:{type:String},
    emails:[emailSchema],
    primaryEmail:{type:String},
    primaryPhone:{type:String},
    phones:[phoneSchema],
    addresses:[addressSchema],
    business:userBusinessSchema,
    memberships:[membershipSchema],
    linkedTo:linkedToSchema,
    tags:[tagsSchema],
    activities:[activitySchema],
    notes:[noteSchema],
    cases:[caseSchema],
    messages:[messageSchema],
    isArchived:{type:Number,default:0},
    transactions:[transactionSchema],
    transactionSummary:transactionSummarySchema,
    creditCards:[creditCardSchema],
    ...timestamps
},{_id:false});

whenever i try to save or find by id and save it sometimes store data or sometime does not store and even does not return error or exception my store code is given below

 const _id = "someprefix-" contact.id;
 let c = new ContactModel({...mongoContact,_id})
    
    try{
     c = await c.save();
     return c;
    }catch(ex){
        try{
            c = await ContactModel.findByIdAndUpdate("someprefix-" _contact.id,{...mongoContact});
            return c;
        }catch(ex){
            return ex;
        }
    }

please help me if anyone have solution.

CodePudding user response:

findByIdAndUpdate will not create a new document if the provided id does not exist yet per default, unless you set the option upsert to true. Try changing your code to:

c = await ContactModel.findByIdAndUpdate("someprefix-" _contact.id,{...mongoContact}, {upsert:true});
  • Related