Skip to content

Commit c11f5f5

Browse files
author
François Daoust
committed
MongoDB and Mongoose quick examples
0 parents  commit c11f5f5

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

mongodb.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
var MongoClient = require('mongodb').MongoClient;
2+
3+
MongoClient.connect('mongodb://127.0.0.1:27017/nodeintro', function (err, db) {
4+
if (err) {
5+
console.error('Oh no, connection troubles!', err);
6+
return;
7+
}
8+
9+
db.collection('testcol').insert({
10+
nick: 'tidoust',
11+
firstName: 'Francois',
12+
lastName: 'Daoust'
13+
}, function (err, result) {
14+
if (err) {
15+
console.error('Insertion failed', err);
16+
process.exit(1);
17+
}
18+
console.log('Inserted', result);
19+
20+
db.collection('testcol').findOne({
21+
nick: 'tidoust'
22+
}, function (err, result) {
23+
if (err) {
24+
console.error('Could not read DB', err);
25+
process.exit(1);
26+
}
27+
console.log('Found', result);
28+
29+
db.close(function (err) {
30+
if (err) return console.error('WTF, no way to close the connection', err);
31+
console.log('That\'s all folks!');
32+
});
33+
});
34+
});
35+
});

mongoose.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
var mongoose = require('mongoose');
2+
var db = mongoose.createConnection('mongodb://localhost:27017/nodeintro');
3+
4+
var userSchema = mongoose.Schema({
5+
nick: String,
6+
age: { type: Number, required: true }
7+
});
8+
9+
userSchema.methods.sayHi = function () {
10+
console.log(this.nick + ' says "Hi!"');
11+
};
12+
13+
var User = db.model('User', userSchema);
14+
15+
db.on('error', console.error.bind(console, 'connection error'));
16+
db.once('open', function callback() {
17+
var user = new User({
18+
nick: 'tidoust',
19+
firstName: 'Francois',
20+
lastName: 'Daoust'
21+
});
22+
23+
user.save(function (err, user) {
24+
if (err) return console.error('Oh no!');
25+
user.sayHi();
26+
27+
console.log(user);
28+
29+
db.close();
30+
});
31+
});

0 commit comments

Comments
 (0)