What Is The Way To Update Or Upsert A Certain Document In Mongoose?

187    Asked by dhanan_7781 in Devops , Asked on Sep 22, 2023

I am facing a lot of issues while updating or updating a document in Mongoose. There’s a contact schema and structure as mentioned below:

var mongoose = require('mongoose'), 

Schema = mongoose.Schema; 

var mongooseTypes = require("mongoose-types"),

useTimestamps = mongooseTypes.useTimestamps; 

var ContactSchema = new Schema({ 

phone: { 

type: String, 

index: { 

unique: true, 

dropDups: true 

}, 

status: { 

type: String, 

lowercase: true, 

trim: true, 

default: 'on' 

}); 

ContactSchema.plugin(useTimestamps); 

var Contact = mongoose.model('Contact', ContactSchema);

I receive a request from the client, containing the fields I need and use my model thusly:

mongoose.connect(connectionString); 

var contact = new Contact({ 

phone: request.phone, 

status: request.status 

});

Now, there are various issues. While I am calling contact. save(function(err){...}), there is an error that a contact having the same phone number pre-exists. I cannot call an update on contact as that method is missing on a document. While calling update on the model: Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...}) 

There is an infinite loop of a few types as the Mongoose update implementation does not allow the object as the second parameter. While passing an associative array of the request properties in the second parameter, it works. However, then, there is no reference to that particular contact, and I am unable to identify its createdAt and updatedAt properties. So, provided a document contact, how to update if it is present and how to insert one if it is missing?


Answered by Dhruv tiwari
  An upsert in MongoDB implies an update in Mongoose that provides a fresh document in case no document is relevant to the filter. If you wish to upsert a certain document in Mongoose, then you need to create the upsert option for the Model. updateOne() function:const res = await Character.  

If you wish to upsert or update a certain document within MongoDB, then it is possible to use the below-mentioned technique. Mongoose supports this with findOneAndUpadte. The upsert = true option sets the object in case it is missing.

var query = {'username':req.user.username};
req.newData.username = req.user.username; MyModel.findOneAndUpdate(query, req.newData, {upsert:true}, function(err, doc){
if (err) return res.send(500, { error: err });
return res.send("succesfully saved");
});

Your Answer

Interviews

Parent Categories