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