Files
biomedjs/node_modules/mongoose/examples/doc-methods.js

78 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2014-09-14 07:04:16 -04:00
2015-11-24 22:08:58 -08:00
var mongoose = require('mongoose');
2014-09-14 07:04:16 -04:00
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Schema
*/
var CharacterSchema = Schema({
2015-11-24 22:08:58 -08:00
name: {
type: String,
required: true
},
health: {
type: Number,
min: 0,
max: 100
}
});
2014-09-14 07:04:16 -04:00
/**
* Methods
*/
2015-11-24 22:08:58 -08:00
CharacterSchema.methods.attack = function() {
2014-09-14 07:04:16 -04:00
console.log('%s is attacking', this.name);
2015-11-24 22:08:58 -08:00
};
2014-09-14 07:04:16 -04:00
/**
* Character model
*/
var Character = mongoose.model('Character', CharacterSchema);
/**
* Connect to the database on localhost with
* the default port (27017)
*/
2015-11-24 22:08:58 -08:00
var dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0);
2014-09-14 07:04:16 -04:00
var uri = 'mongodb://localhost/' + dbname;
console.log('connecting to %s', uri);
2015-11-24 22:08:58 -08:00
mongoose.connect(uri, function(err) {
2014-09-14 07:04:16 -04:00
// if we failed to connect, abort
if (err) throw err;
// we connected ok
example();
2015-11-24 22:08:58 -08:00
});
2014-09-14 07:04:16 -04:00
/**
* Use case
*/
2015-11-24 22:08:58 -08:00
function example() {
Character.create({ name: 'Link', health: 100 }, function(err, link) {
2014-09-14 07:04:16 -04:00
if (err) return done(err);
console.log('found', link);
link.attack(); // 'Link is attacking'
done();
2015-11-24 22:08:58 -08:00
});
2014-09-14 07:04:16 -04:00
}
/**
* Clean up
*/
2015-11-24 22:08:58 -08:00
function done(err) {
2014-09-14 07:04:16 -04:00
if (err) console.error(err);
2015-11-24 22:08:58 -08:00
mongoose.connection.db.dropDatabase(function() {
2014-09-14 07:04:16 -04:00
mongoose.disconnect();
2015-11-24 22:08:58 -08:00
});
2014-09-14 07:04:16 -04:00
}