Two methods to connect to Mongo DB

  • mongoose.connect

  • mongoose.createConnection

1
2
3
4
5
6
const dbURL = 'mongodb://...'
const dbOptions = {
user: 'db_user',
pass: 'db_pass'
}
const adminConnection = mongoose.createConnection(dbURL, dbOptions)

Close Connection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mongoose.connection.close(() => {
console.log('Connection cvlosed')
})

adminConnection.close(() => {
console.log('adminConnection closed')
})

// auto close when process exit
process..on('SIGINT' () => {
mongoose.connection.close(() => {
console.log('Mongoose disconnected through app termination')
process.exit(0)
})
})

Cache Error

1
2
3
mongoose.connection.on('error', (err) => {
console.log('Mongoose connection error: ' + err)
})

db.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
// /model/db.js
const mongoose = require('mongoose')

const dbURL = 'mongodb://...'

mongoose.connect(dbURL)

mongoose.connection.on('connected', () => {
console.log('Mongoose connected to ' + dbURL)
})

mongoose.connection.on('error', (err) => {
console.log('Mongoose connection error: ' + err)
})

mongoose.connection.on('disconnected', () => {
console.log('Mongoose disconnected')
})

process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('Mongoose disconnected through app termination')
})
})

// app.js
db = require('./model/db')

Schema and Model in Mongoose

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

1
2
3
4
5
6
7
8
const Schema = mongoose.Schema
const userSchema = new Schema({
name: String,
pass: String,
email: String,
createTime: String,
lastLogin: String,
})

Schema to define table structure.

Model to manipulate collection.

Use model to create documents in Mongodb.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// create model
const User = mongoose.model('User', userSchema)

// create instance, namely document
const newUser = new User({
...
})

// insert document to db
newUser.save((err, doc) => {
err && console.error(err)
console.log('doc is saved')
})

// create and insert
User.create({...}, (err, doc) => {
err && console.error(err)
console.log('doc saved')
})

// add staitc methods
userSchema.statics.findUsersByType = function (type, cb) {
return this.find({ type: this.type }, cb)
}
  • Model.$where(argument: string | Function): , creates a Query and specifies a $where condition
1
Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {})
  • Model#increment()
1
User.find({ type: 'type' }).where('age').gt(2).limit(10).exec()

remove

1
2
3
User.remove({ type: 'type' }, (err, res) => {
err && console.error(err)
})

update

1
2
3
4
5
6
7
User.find({ type: 'type' }).update({
$set: {
date: new Date()
}
}, (err) => {
err && console.error(err)
})

Moreā€¦