Last active
August 29, 2015 14:06
-
-
Save niusounds/e2f3d55ffb78161dfb3d to your computer and use it in GitHub Desktop.
Simple Mongoose example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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