Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I update/upsert a document in Mongoose?
    primarykey
    data
    text
    <p>Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :)</p> <p>Here's the deal: </p> <p>I have a contact schema and model (shortened properties):</p> <pre><code>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); mongoose.model('Contact', ContactSchema); //is this line superflous?? var Contact = mongoose.model('Contact', ContactSchema); </code></pre> <p>I receive a request from the client, containing the fields I need and use my model thusly:</p> <pre><code>mongoose.connect(connectionString); var contact = new Contact({ phone: request.phone, status: request.status }); </code></pre> <p>And now we reach the problem:</p> <ol> <li>If I call <code>contact.save(function(err){...})</code> I'll receive an error if the contact with the same phone number already exists (as expected - unique)</li> <li>I can't call <code>update()</code> on contact, since that method does not exist on a document</li> <li>If I call update on the model:<br> <code>Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})</code><br> I get into an infinite loop of some sorts, since the Mongoose update implementation clearly doesn't want an object as the second parameter.</li> <li>If I do the same, but in the second parameter I pass an associative array of the request properties <code>{status: request.status, phone: request.phone ...}</code> it works - but then I have no reference to the specific contact and cannot find out its <code>createdAt</code> and <code>updatedAt</code> properties.</li> </ol> <p>So the bottom line, after all I tried: given a document <code>contact</code>, how do I update it if it exists, or add it if it doesn't?</p> <p>Thanks for your time.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload