纯mongoose练习
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// 27017为mongodb的默认端口号
// mongodb中的表叫集合(collection)
// 创建一个model,在mongoose中一个model是和数据库集合进行关联
// Schema为数据模型创建一个数据结构
const personSchema = new Schema({
name: {
type: String,
// 必须输入信息
required: true,
},
age: {
type: Number,
// 表示默认值尾0
default: 0,
},
skills: {
type: String,
default: "",
},
avatars: {
type: String,
default: "",
},
}, {
timestamps: true, // 为每一条记录添加一个新增和修改的时间戳
});
const Person = mongoose.model("person", personSchema); // 创建模型
// 就是mongodb是非关系数据库
// 他里面的每一条数据都是可以不固定的
// 比如这一条数据是username。下一条数据可以是age 或者sex
// 而不用固定为一个表全是username
// model就是为了限制他们
mongoose
.connect("mongodb://localhost:27017/vip-cartoons", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((res) => {
console.log("数据库连接成功");
// const person = new Person({
// name: "Naruto",
// avatars: "",
// age: 17,
// skills: "多重影分身",
// });
// save方法有更新和插入两种功能,到底是插入还是更新文档取决于save的参数。
// person.save().then((d) => {
// console.log("保存成功");
// });
// .find({}) 找到所有数据内容
// Person.find({}).then((d) => console.log(d));
// const sss = [
// {
// name: "大蛇丸",
// skills: "",
// },
// {
// name: "纲手",
// },
// {
// name: "自来也",
// },
// ];
// .insertMany在集合中添加一批记录
// Person.insertMany(sss).then((d) => {
// console.log(d);
// });
// Person.find // 根据条件查找,返回一个数组
// Person.findOne // 根据条件查找,返回一个
// Person.findById // 根据id查找
// .save // 保存
// Person.findByIdAndDelete // 根据id删除
// Person.findByIdAndUpdate // 根绝id修改
})
.catch((err) => {
console.log(err);
});
demo
app.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.use(express.json()); // 让express能够格式化请求体中的json数据
const fs = require("fs");
if (!fs.existsSync("./db")) {
fs.mkdirSync("./db");
}
app.use("/", express.static("./public"));
// app.use("/api/v1/pets", require("./routes/api/v1/pets"));
// app.use("/api/v1/movies", require("./routes/api/v1/movies"));
app.use("/api/v1/people", require("./routes/api/v1/people"));
app.listen(3335, () => {
console.log("服务器运行在3335端口");
mongoose
// 27017 是数据库默认的端口号
.connect("mongodb://localhost:27017/vip-cartoons", {
// 这两个参数 是让终端多出来的那几行代码去掉,要不看着挺乱,没有这两个也是可以的
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("数据库连接成功"));
});
person.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const personSchema = new Schema(
{
name: {
type: String,
required: true,
},
age: {
type: Number,
default: 0,
},
skills: {
type: String,
default: "",
},
avatars: {
type: String,
default: "",
},
},
{
timestamps: true, // 为每一条记录添加一个新增和修改的时间戳
}
);
const Person = mongoose.model("person", personSchema);
module.exports = Person;
people.js
// 路由是让你能根据你定义的路由名称来匹配接口的
const router = require("express").Router();
// 文件名的后缀可以省略
const Person = require("../../../models/person");
// async/await
// async和await是成对出现的
// await必须放在async修饰的方法内部
// await后面跟一个promise操作,等待promise成功调用
router.get("/", async (req, res) => {
// Person.find({}).then((data) => {
// res.json({
// code: 1,
// msg: "获取数据成功",
// data, // data: data
// });
// });
const data = await Person.find({}).sort({
_id: -1
});
res.json({
code: 1,
msg: "获取数据成功",
data,
});
});
// /api/v1/pets/1
router.get("/:id", async (req, res) => {
// res.json({
// code: 1,
// msg: "获取单条数据成功",
// });
// try/catch做异常处理
try {
const data = await Person.findById(req.params.id);
res.json({
code: 1,
msg: "获取数据成功",
data,
});
} catch (err) {
res.json({
code: 0,
err,
});
}
});
router.post("/", async (req, res) => {
const person = new Person(req.body);
await person.save();
res.json({
code: 1,
msg: "新增数据成功",
});
});
router.put("/:id", async (req, res) => {
await Person.findByIdAndUpdate(req.params.id, req.body);
res.json({
code: 1,
msg: "修改数据成功",
});
});
router.delete("/:id", async (req, res) => {
await Person.findByIdAndDelete(req.params.id);
res.json({
code: 1,
msg: "删除数据成功",
});
});
module.exports = router;