arnaucube
arnaucube/thoughtsPublic Self-hosted repository
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: {
13    type: String,
14    required: true
15  },
16  health: {
17    type: Number,
18    min: 0,
19    max: 100
20  }
21});
22
23/**
24 * Methods
25 */
26
27CharacterSchema.methods.attack = function() {
28  console.log('%s is attacking', this.name);
29};
30
31/**
32 * Character model
33 */
34
35var Character = mongoose.model('Character', CharacterSchema);
36
37/**
38 * Connect to the database on localhost with
39 * the default port (27017)
40 */
41
42var dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0);
43var uri = 'mongodb://localhost/' + dbname;
44
45console.log('connecting to %s', uri);
46
47mongoose.connect(uri, function(err) {
48  // if we failed to connect, abort
49  if (err) throw err;
50
51  // we connected ok
52  example();
53});
54
55/**
56 * Use case
57 */
58
59function example() {
60  Character.create({name: 'Link', health: 100}, function(err, link) {
61    if (err) return done(err);
62    console.log('found', link);
63    link.attack(); // 'Link is attacking'
64    done();
65  });
66}
67
68/**
69 * Clean up
70 */
71
72function done(err) {
73  if (err) console.error(err);
74  mongoose.connection.db.dropDatabase(function() {
75    mongoose.disconnect();
76  });
77}