Skip to content

Instantly share code, notes, and snippets.

@niusounds
Last active August 29, 2015 14:06
Show Gist options
  • Save niusounds/e2f3d55ffb78161dfb3d to your computer and use it in GitHub Desktop.
Save niusounds/e2f3d55ffb78161dfb3d to your computer and use it in GitHub Desktop.
Simple Mongoose example
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp');
var schema = new mongoose.Schema({
name: String,
created: {
type: Date,
'default': Date.now
},
updated: Date
}).pre('save', function(next) {
this.updated = new Date();
next();
});
var model = mongoose.model('MyModel', schema);
new model({
name: 'Taro'
}).save(function(err, saved) {
if (err) throw err;
setTimeout(function() {
console.log('generated ID : ', saved._id);
model.findById(saved._id, function(err, data) {
if (err) throw err;
data.name = 'Jiro';
data.save(function(err, updated) {
if (err) throw err;
console.log('updated', updated);
});
});
}, 1000);
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp');
var schema = new mongoose.Schema({
name: String
});
var model = mongoose.model('MyModel', schema);
new model({
name: 'Taro'
}).save(function(err) {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment