About this question
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?