Skip to content

Instantly share code, notes, and snippets.

@tblobaum
Created September 24, 2011 05:39
Show Gist options
  • Save tblobaum/1239016 to your computer and use it in GitHub Desktop.
Save tblobaum/1239016 to your computer and use it in GitHub Desktop.
UserSchema = new Schema({
created: {type:Date, default:Date.now},
last_update: {type:Date, default:Date.now},
name: {type:String, default:'anonymous'},
email: {type:String, default:'none', lowercase:true, index:true},
});
User = Mongoose.model('User', UserSchema);
var doc = {
_id: '4e6121...',
name: 'Your Name',
email: 'email@gmail.com',
last_update: new Date()
};
// if doc contains an _id field just send it through
new User(doc).upsert();
// if doc has an _id field, but you want to check the error yourself you
// can supply a callback as a single argument
new User(doc).upsert(function (e) {
if (e) console.log(e);
});
// if doc does not have an _id field, but you have access to
// it as a string, you can use this
new User(doc).upsert('4e6121...');
// or you can supply the _id as a string for the first field and a callback
new User(doc).upsert('4e6121...', function (e) {
if (e) console.log(e);
});
// supply an object as the first argument, which contains the search
// query or what to look for, and it will be updated with doc
new User(doc).upsert({apikey: '81da51e88199139e0e9cc56464607411' }, function (e) {
if (e) console.log(e);
});
// if doc contains an _id field, and you would like to make changes
// to dirty data but *not* update the entire doc, you can pass in the changes
// as the first parameter with a callback
new User(doc).upsert({$set : { name: 'name change' } }, function (e) {
if (e) console.log(e);
});
// you can also pass in three arguments, what to look for, what to
// update, and the callback
new User(doc).upsert({apikey: '81da51e88199139e0e9cc56464607411' }, {$set : { name: 'new name' } }, function (e) {
if (e) console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment