mongoose連接mongodb
創(chuàng)建Schema和model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
author: String,
year: Number
});
//mongoose.model 創(chuàng)建一個 Schema 的實例
module.exports = mongoose.model('Book', BookSchema);
連接到MongoDB
var connection = mongoose.connection;
# 這個是數(shù)據(jù)庫地址
var db = 'mongodb://james:123456@localhost:27017/example';
// 連接
mongose.connect(db);
// 連接后的事件 這里主要用來表示是否成功連接到數(shù)據(jù)庫
connection.on('connected', function() {
console.log('Mongoose 連接到 example數(shù)據(jù)庫');
})
connection.once('open', function(callback){
console.log('數(shù)據(jù)庫啟動了');
// app.listen(8080, () => console.log('Express server listening on port 8080'));
})
實例操作
數(shù)據(jù)庫的操作通常就是 create | remove | update | delete, 也就是常說的 '增刪改查'。
1.創(chuàng)建數(shù)據(jù)模型
// Book.model.js
var mongoose = require('mongoose')
var Schema = mongoose.Schema
// Schema相當(dāng)于數(shù)據(jù)骨架
var BookSchema = new Schema({
title: {
type: String,
required: true
},
author: String,
category: String
//publishDate: {
// type: Date,
// default: Date.now
//}
});
// mongoose.model 表示實例化Schema
module.exports = mongoose.model('Book', BookSchema);
關(guān)于 schema的類型定義, mongoose doc
2.操作數(shù)據(jù)
使用 'express','body-parser'
// app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser'); // 獲取URL中的參數(shù)
var mongoose = require('mongoose');
var Book = require('./Book.model');
app.use(bodyParser.json()); // 用來解析json數(shù)據(jù)格式
// extended 布爾值的含義
// true: 表示使用 'querystring' 庫來解析 url-encoded 數(shù)據(jù)
// false: 表示使用 'qs' 庫來解析
app.use(bodyParser.urlencoded({
extended: true
}));
// example 為 數(shù)據(jù)庫名
var db_url = 'mongodb://james:123456@localhost:27017/example';
// 連接mongodb
mongoose.connect(db_url);
mongoose.connection.on('connected', function() {
console.log('Mongoose connection open to example');
})
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error ' + err);
})
mongoose.connection.once('open', function(callback){
console.log('數(shù)據(jù)庫啟動了');
// app.listen(8080, () => console.log('Express server listening on port 8080'));
})
var port = 8080;
app.get('/', function(req, res) {
res.send('hello');
})
// get請求 查詢數(shù)據(jù) find()
app.get('/books', function(req, res) {
console.log('getting all books');
Book.find({})
.exec(function(err, books) {
if (err) {
console.log('err',err);
res.send('error has occured');
} else {
res.json(books);
console.log(books);
}
})
})
// get請求 查詢數(shù)據(jù) findOne()
app.get('/books/:id', function(req, res) {
console.log('get one book');
Book.findOne({ // 查詢單個
_id: req.params.id
})
.exec(function(err, book) {
console.log('get one book');
if (err) {
res.send(err);
} else {
res.json(book);
console.log('get book')
}
})
})
// post請求 新增一條數(shù)據(jù) save
// 此處使用表單的形式,(使用 'x-www-form-urlencoded')將參數(shù)添加到url中
// 然后使用postman 模擬表單提交
app.post('/book', function(req, res) {
// 實例化一個文檔對象
var newBook = new Book();
// 使用bodyParser對url參數(shù)進行解析
newBook.title = 'req.body.title';
newBook.author = req.body.author;
newBook.category = req.body.category;
newBook.save(function(err, book) {
if (err) {
res.send(err);
} else {
console.log(book);
res.send(book);
}
});
});
// 'put'請求 修改數(shù)據(jù) findByIdAndUpdate
app.put('/book/:id', function(req, res) {
Book.findByIdAndUpdate(req.params.id,
{$set: { title: req.body.title }},
{new: true},
function(err, book) {
if (err) {
res.send(err);
} else {
res.send(book);
}
}
)
});
// 'delete'請求 刪除數(shù)據(jù) findOneAndRemove
app.delete('/book/:id', function(req, res) {
Book.findOneAndRemove({
_id: req.params.id,
}, function(err, book) {
if (err) {
console.log(err);
res.send(err);
} else {
console.log(book);
res.send(book);
}
})
})
app.listen(port, function() {
console.log('app listening on port ' + port);
})
mongoose對數(shù)據(jù)庫的操作函數(shù)和MongoDB類似,這個查看官方文檔即可。
另外postman 模擬請求:

postman模擬post請求.png
mongoose 使用 promise
因為mongoose內(nèi)置的promise庫已經(jīng)是廢棄狀態(tài),我們可以使用 bluebird 等promise庫讓mongoose支持promise
// 安裝bluebird步驟已省略
// 使mongoose支持promise寫法
mongoose.Promise = require('bluebird');
// 然后可以使用promise風(fēng)格書寫代碼
// get請求 查詢數(shù)據(jù) findOne()
app.get('/books/:id', function(req, res) {
console.log('get one book');
Book.findOne({ // 查詢單個
_id: req.params.id
})
.exec(function(err, book) {
console.log('get one book');
if (err) {
res.send(err);
} else {
res.json(book);
console.log('get book')
}
})
})
// 可以改寫為
// get請求 查詢數(shù)據(jù) findOne()
app.get('/books/:id', function(req, res) {
console.log('get one book');
Book.findOne({ // 查詢單個
_id: req.params.id
})
.exec()
then(function(book) {
res.json(book)
})
.catch(err => res.send(err))
})