forked from annette-arrigucci/mongoose-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetting-started.js
89 lines (71 loc) · 2.45 KB
/
getting-started.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
console.log("We're connected!");
var kittySchema = mongoose.Schema({
name: String
});
//var silence = new Kitten({ name: 'Silence' });
// console.log(silence.name); // 'Silence'
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
//fluffy.speak(); // "Meow name is fluffy"
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
//fluffy.speak();
console.log("Saved "+ fluffy.name);
});
var garfield = new Kitten({ name: 'Garfield' });
//fluffy.speak(); // "Meow name is fluffy"
garfield.save(function (err, garfield) {
if (err) return console.error(err);
//fluffy.speak();
console.log("Saved "+ garfield.name);
});
Kitten.find(function (err, kittens) {
if (err) return console.error(err);
console.log("All kittens in database: " + kittens);
});
Kitten.find({ name: /^fluff/ }, function (err, fluffKittens) {
if (err) return console.error(err);
console.log("Kittens with names starting with fluff: " + fluffKittens);
});
Kitten.find({ name: /^Gar/ }, function (err, garKittens) {
if (err) return console.error(err);
console.log("Kittens with names starting with Gar: " + garKittens);
});
});
/*var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var silence = new Kitten({ name: 'Silence' });
console.log(silence.name); // 'Silence'
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});
Kitten.find(function (err, kittens) {
if (err) return console.error(err);
console.log(kittens);
})
Kitten.find({ name: /^fluff/ }, callback);*/