安装到 C:\Program Files
c盘新建 C:\data\db
找到 bin 目录(C:\Program Files\mongodb-windows-x86_64-5.0.19\mongodb-win32-x86_64-windows-5.0.19\bin)
.每次启动麻烦可下载 msi 文件,一键安装即可
show dbs
use 数据库名
db;
db.dropDatabase();
db("db_name").createCollection("collection");
db.createCollection("user");
show collections
db.user.drop();
db.user.renameCollection("users");
db.users.insert({ name: "xr", age: 20 });
db.users.find();
db.users.update(查询条件,新的文档)
db.users.update({age:20},{$set:{age:18}})
db.users.drop(查询条件);
npm install mongoose
const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/db_name");
mongoose.connection.once("open", () => {
console.log("链接成功");
});
mongoose.connection.on("error", () => {
console.log("链接失败");
});
mongoose.connection.on("close", () => {
console.log("链接关闭");
});
setTimeout(() => {
// 测试关闭连接
mongoose.disconnect();
}, 2000);
promise 风格连接
const mongoose = require("mongoose");
mongoose
.connect("mongodb://127.0.0.1:27017/db_name")
.then((res) => {
console.log("连接成功");
})
.catch((err) => {
console.log(err);
});
常用字段类型
类型 | 描述 |
---|---|
String | 字符串 |
Number | 数字 |
Boolean | 布尔值 |
Array | 数组也可使用 [] |
Date | 日期 |
Buffer | Buffer 对象 |
Mixed | 任意类型,mongoose.Schema.Typea.Mixed |
ObjectId | 对象 id,mongoose.Schema.Typea.ObjectId |
Decimal128 | 高精度数字,mongoose.Schema.Typea.Decimal128 |
创建 Schema
const Schema = new mongoose.Schema({
name: {
type: String,
// 必填项
required: true,
// 默认值
default: '默认值',
// 枚举值
enum:['男','女']
// 唯一值
unique: true,
// 查询时不展示此字段
select: false
},
}, {
// 添加创建 更新时间字段
timestamps: true,
});
mongoose.connection.once("open", async () => {
// 创建文档结构对象
const Schema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: Number,
isAdmin: Boolean,
tags: Array,
createTime: {
type: Date,
default: new Date(),
},
mixed: mongoose.Schema.Types.Mixed,
});
// 创建数据模型
const UserModel = mongoose.model("users", Schema);
// 新增
const data = await UserModel.create({
name: "李四",
age: 28,
isAdmin: true,
tags: ["JavaScript", "Node"],
mixed: "test",
});
});
增
const data = await UserModel.create({
name: "李四",
age: 28,
isAdmin: true,
tags: ["JavaScript", "Node"],
mixed: "test",
});
删
deleteOne(条件);
const data = await UserModel.deleteOne({ name: "张三" });
const data = await UserModel.deleteMany({ name: "xm" });
改
updateOne(条件, 更改值);
const data = await UserModel.updateOne({ _id: "64b567014b5d8e70416465dd" }, { isAdmin: false });
const data = await UserModel.updateMany({ name: "李四" }, { isAdmin: false });
查
const data = await UserModel.findOne({ _id: "64b560dcf9d01fd3a213a5d1" });
const data = await UserModel.findById("64b560dcf9d01fd3a213a5d1");
const data = await UserModel.find({ name: "李四" });
运算符
运算符 | 替代 |
---|---|
> | $gt |
< | $lt |
>= | $gte |
<= | $lte |
!== | $ne |
// 查询 age >= 26
const data = await UserModel.find({ age: { $gte: 26 } });
逻辑运算符
$or
逻辑或
// 查询 age = 26,或者 age = 27
const data = await UserModel.find({ $or: [{ age: 26 }, { age: 27 }] });
$and
逻辑与
// 查询 age = 26,并且 nme = "李四"
const data = await UserModel.find({ $and: [{ age: 26 }, { name: "李四" }] });
正则匹配
// 查询 name 包含 李,可用作模糊查询
const data = await UserModel.find({ name: /李/ });
const data = await UserModel.find({ name: new RegExp("李") });
字段筛选,查询数据隐藏某些字段 select
0 不要的字段 1 需要的字段
const data = await UserModel.find({ name: "xr" }).select({ isAdmin: 0 }).exec();
数据排序 sort
1 升序 -1 倒序
// 查询根据年龄升序
const data = await UserModel.find().sort({ age: 1 }).exec();
数据截取, 可用来分页
skip 跳过 limit 限定
const data = await UserModel.find().skip(1).limit(1).exec();
const page = 3;
const limit = 1;
const data = await UserModel.find()
.skip((page - 1) / limit)
.limit(limit)
.exec();
表结构
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
name: String,
age: Number,
sex: Number,
},
{
timestamps: true,
}
);
const UserModel = mongoose.model("user", UserSchema);
const ArticleSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
desc: String,
tag: Array,
// 返回一个对象 author: { ... }
// author:类型是 ObjectId 值是 user 表数据 _id,
// ref: 连接的表名
author: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
// 返回结构是一个数组套对象 [{ ... }]
// author: [{ type: mongoose.Schema.Types.ObjectId, ref: "user" }],
},
{
timestamps: true,
}
);
const ArticleModel = mongoose.model("article", ArticleSchema);
module.exports = {
UserModel,
ArticleModel,
};
查询
const { UserModel, ArticleModel } = require("../model/index");
class IndexController {
async getArticle(ctx) {
try {
// 字符串参数写法
// select:显示 name 字段,隐藏 _id 字段
// const data = await ArticleModel.find().populate("author","name -_id").exec();
// 对象参数写法
const data = await ArticleModel.find().populate({ path: "author", select: "name -_id" }).exec();
ctx.body = {
data,
};
} catch (error) {
console.error(error);
}
}
}
module.exports = new IndexController();