thoughts/node_modules/mongoose/examples/doc-methods.js
node_modules/mongoose/examples/doc-methods.jsRaw
1
2var mongoose = require('mongoose')
3var Schema = mongoose.Schema;
4
5console.log('Running mongoose version %s', mongoose.version);
6
7/**
8 * Schema
9 */
10
11var CharacterSchema = Schema({
12 name: { type: String, required: true }
13 , health: { type: Number, min: 0, max: 100 }
14})
15
16/**
17 * Methods
18 */
19
20CharacterSchema.methods.attack = function () {
21 console.log('%s is attacking', this.name);
22}
23
24/**
25 * Character model
26 */
27
28var Character = mongoose.model('Character', CharacterSchema);
29
30/**
31 * Connect to the database on localhost with
32 * the default port (27017)
33 */
34
35var dbname = 'mongoose-example-doc-methods-' + ((Math.random()*10000)|0);
36var uri = 'mongodb://localhost/' + dbname;
37
38console.log('connecting to %s', uri);
39
40mongoose.connect(uri, function (err) {
41 // if we failed to connect, abort
42 if (err) throw err;
43
44 // we connected ok
45 example();
46})
47
48/**
49 * Use case
50 */
51
52function example () {
53 Character.create({ name: 'Link', health: 100 }, function (err, link) {
54 if (err) return done(err);
55 console.log('found', link);
56 link.attack(); // 'Link is attacking'
57 done();
58 })
59}
60
61/**
62 * Clean up
63 */
64
65function done (err) {
66 if (err) console.error(err);
67 mongoose.connection.db.dropDatabase(function () {
68 mongoose.disconnect();
69 })
70}