官方文檔: https://mongoosejs.com/docs/index.html
安裝
npm install mongoose --save
基本使用
// 1. 引入包
const mongoose = require("mongoose");
// 2. 連接數(shù)據(jù)庫(kù)
mongoose.connect('mongodb://127.0.0.1/test_db');
// 3. 獲取數(shù)據(jù)庫(kù)連接對(duì)象
const connection = mongoose.connection;
/**
* 4. 監(jiān)聽(tīng)數(shù)據(jù)庫(kù)狀態(tài)
**/
// 監(jiān)聽(tīng)數(shù)據(jù)庫(kù)的連接的打開(kāi)和關(guān)閉
connection.once("open", () => {
console.log("數(shù)據(jù)庫(kù)連接成功");
});
connection.once("close", () => {
console.log("數(shù)據(jù)庫(kù)已經(jīng)關(guān)閉連接");
});
// 監(jiān)聽(tīng)數(shù)據(jù)庫(kù)錯(cuò)誤
connection.on("error", error => {
console.log("數(shù)據(jù)庫(kù)錯(cuò)誤|Database error:" + error);
});
// 5. 創(chuàng)建Schema(模式對(duì)象) 類(lèi)似于SQL中的設(shè)計(jì)表字段約束(此處的Schema注意大寫(xiě))
let userSchema = new mongoose.Schema({
name : String,
age: Number,
sex: {
type: String,
default: "男"
},
height: Number
});
// 6. 創(chuàng)建model對(duì)象 model("collectionName", "documents")
// 注意: 此處的 collectionName會(huì)自動(dòng)轉(zhuǎn)換為復(fù)數(shù)形式
let userModel = mongoose.model("users", catSchema);
// 7. 插入一條數(shù)據(jù)到 users 這個(gè)集合中
userModel.create({ name : "zs", age: 18, height: 172 }, error => {
if (error) throw error;
console.log("插入成功");
});
插入數(shù)據(jù)
// 插入一條數(shù)據(jù)
userModel.create([ { name : "zs", age: 18, height: 172 } ], error => {
if (error) throw error;
console.log("插入成功");
});
// 一次插入多個(gè)數(shù)據(jù)
userModel.create([
{ name : "zs", age: 18, height: 172 },
{ name : "ls", age: 20, height: 176 },
{ name : "wc", age: 28, height: 178 },
{ name : "ml", age: 32, height: 168 }
], error => {
if (error) throw error;
console.log("插入成功");
});
刪除數(shù)據(jù)
userModel.remove({name: 'ml'}, error => {
if (error) throw error;
console.log("刪除成功");
});
修改數(shù)據(jù)
userModel.update({'name' : 'zs'}, { $set: {height: 182} }, error => {
if (error) throw error;
console.log("修改成功");
});
查詢數(shù)據(jù)
// 帶條件條件的查詢
userModel.find({name: 'zs'}, (error, docs) => {
if (error) throw error;
console.log(docs);
});
- 查詢數(shù)據(jù),限制顯示字段并且跳過(guò)前兩個(gè)顯示一個(gè)
// db.users.find({}, {_id:0, __v:0}).skip(2).limit(1);
userModel.find( {}, { _id: 0, __v:0 }, { skip:2, limit: 1 }, (error, docs) => {
if (error) throw err;
console.log(docs);
});