mongoose 使用
Mongoose 基礎(chǔ)使用
- Connect 鏈接數(shù)據(jù)庫
- 定義文檔模型, Schema 和 model 新建模型
- 定義一個(gè)數(shù)據(jù)庫文檔對(duì)應(yīng)一個(gè)模型, 通過模型對(duì)數(shù)據(jù)庫進(jìn)行操作
// 引入依賴
const mongoose = require("mongoose");
// 鏈接mongo 并且使用 hank 這個(gè)集合
const DB_URL = "mongodb://localhost:27017/hank";
mongoose.connect(DB_URL);
mongoose.connection.on("connected", () => {
console.log("mongo connect success");
});
// 類似于 MySQL 的表, mongo 里有文檔, 字段的概念
const User = mongoose.model(
"user",
new mongoose.Schema({
user: {
type: String,
require: true
},
age: {
type: Number,
require: true
}
})
);
// 新增數(shù)據(jù)
User.create({
user: 'hank',
age: 18
}, (err, doc) => {
if (!err) {
console.log(doc)
} else {
console.log(err)
}
})
// 刪除數(shù)據(jù)
User.remove({age: 18}, (err, doc) => {
if (!err) {
console.log('delete success')
console.log(doc)
}
})
// 更新
User.update({'user':'hank'}, {'$set': {'age': 17}}, (err, doc) => {
console.log(doc)
})
const app = express()
app.get('/', (req, res) => {
// 查詢
User.find({}, (err, doc) => {
if (!err) {
res.json(doc)
}
})
User.findOne({}, (err, doc) => {
if (!err) {
res.json(doc)
}
})
})
app.listen(9093, () => {
console.log('Server running http://localhost:9093')
})
Mongoose 文檔類型
- String, Number 等數(shù)據(jù)結(jié)構(gòu)
- 定 create, remove, update 分別用來增, 刪, 改的操作
- Find findOne 查詢數(shù)據(jù)