UNPKG

1.3 kBJavaScriptView Raw
1
2'use strict';
3const mongoose = require('mongoose');
4const Schema = mongoose.Schema;
5
6console.log('Running mongoose version %s', mongoose.version);
7
8/**
9 * Schema
10 */
11
12const 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 * Methods
26 */
27
28CharacterSchema.methods.attack = function() {
29 console.log('%s is attacking', this.name);
30};
31
32/**
33 * Character model
34 */
35
36const Character = mongoose.model('Character', CharacterSchema);
37
38/**
39 * Connect to the database on localhost with
40 * the default port (27017)
41 */
42
43const dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0);
44const uri = 'mongodb://localhost/' + dbname;
45
46console.log('connecting to %s', uri);
47
48mongoose.connect(uri, function(err) {
49 // if we failed to connect, abort
50 if (err) throw err;
51
52 // we connected ok
53 example();
54});
55
56/**
57 * Use case
58 */
59
60function 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(); // 'Link is attacking'
65 done();
66 });
67}
68
69/**
70 * Clean up
71 */
72
73function done(err) {
74 if (err) console.error(err);
75 mongoose.connection.db.dropDatabase(function() {
76 mongoose.disconnect();
77 });
78}