Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Devops
  3. Question
Devops

How do I update/upsert a document in Mongoose?

Asked by Liam Nelson Jul 18, 2021 4.7K views 1 answer
Share

About this question

 I am struggling with document upsert issue in mongoose.

Here's the deal:

I have a contact schema and model (shortened properties):

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 
});

And now we reach the problem:

  1. If I call contact.save(function(err){...}) I'll receive an error if the contact with the same phone number already exists (as expected - unique)

  2. I can't call update() on contact since that method does not exist on a document

  3. If I call update on the model:
    Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})
    I get into an infinite loop of some sorts since the Mongoose update implementation clearly doesn't want an object as the second parameter.

  4. If I do the same, but in the second parameter I pass an associative array of the request properties {status: request.status, phone: request. phone ...} it works - but then I have no reference to the specific contact and cannot find out its createdAt and updatedAt properties.

So the bottom line, after all, I tried: given a document contact, how do I update it if it exists, or add it if it doesn't?

 

Your answer

1 Answer

More Devops discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest DevOps Blogs

Guides, tips and career advice on DevOps from JanBask experts.