使用 Mongoose 简单的建立一个博客数据库以及模型之间的关联。
bash
1mkdir -p mongoose-model
2cd mongoose-model
3npm init -y
4npm i mongoose
5touch index.jsCOPY
首先建立对数据库的连接。
js
1const mongoose = require("mongoose");
2mongoose.connect("mongodb://127.0.0.1:27017/moogose-model-demo", {
3 useNewUrlParser: true
4});COPY
建立 Post 模型。
js
1const Post = mongoose.model(
2 "Post", // 模型名称
3 new mongoose.Schema({
4 title: String,
5 categories: [ // 分类与分类模型相关联
6 {
7 type: mongoose.SchemaTypes.ObjectId, // 关联分类模型中的唯一 _id
8 ref: "Category" // 关联的模型名称
9 }
10 ]
11 })
12);COPY
建立 Category 模型。
js
1const Category = mongoose.model(
2 "Category",
3 new mongoose.Schema({
4 name: String
5 })
6);COPY
插入几条数据。
js
1Post.insertMany([{
2 title: "第 1 条",
3},{
4 title: "第 2 条",
5}])
6Category.insertMany([{
7 name: "vuejs"
8},{
9 name: "nodejs"
10}])COPY
之所以要进行关联,是因为为了后期维护和可操作性。
对 Post 加入分类字段与之关联。
js
1;(async function() {
2 const cate1 = await Category.findOne({
3 name: "vuejs"
4 });
5 const cate2 = await Category.findOne({
6 name: "nodejs"
7 });
8 const post1 = await Post.findOne({
9 title: "第1篇帖子"
10 });
11 const post2 = await Post.findOne({
12 title: "第2篇帖子"
13 });
14
15 post1.categories = [cate1, cate2]; // 直接赋值即可
16 post2.categories = [cate1];
17 await post1.save(); // 保存修改
18 await post2.save();
19 const posts = await Post.find().populate("categories");
20 // console.log(posts[0], posts[1]);
21})();COPY
首先把 Post 和 Category 找出来,然后把分类字段改掉,最后别忘了保存。
populate()可以跟踪关联的_id,输出详细的内容。
输出内容如下:
js
1{
2 categories: [
3 { _id: 5d30626d7fc5f875b856e403, name: 'vuejs', __v: 0 },
4 { _id: 5d30626d7fc5f875b856e402, name: 'nodejs', __v: 0 }
5 ],
6 _id: 5d3061a43f97af74e8e62f38,
7 title: '第1篇帖子',
8 __v: 22
9} {
10 categories: [ { _id: 5d30626d7fc5f875b856e403, name: 'vuejs', __v: 0 } ],
11 _id: 5d3061bb5617a5750523af66,
12 title: '第2篇帖子',
13 __v: 22
14}COPY
因为分类模型中不存在对 Post 的记录所以查询的时候要建立虚拟字段。首先要修改 Category 的模型。
js
1CategorySchema.virtual("posts", {
2 // 定义一个虚拟字段
3 ref: "Post", // 关联的模型
4 localField: "_id", // 内建 ☞Category 的键
5 foreignField: "categories", // 外键 ☞ Post 的键
6 justOne: false // 结果只有一条还是多条
7});
8const Category = mongoose.model("Category", CategorySchema);COPY
修改之后直接就可以查询到了。
js
1;(async function() {
2 const cates = await Category.find()
3 .populate("posts")
4 // .lean();
5 console.log(cates[0].posts, cates[1].posts);
6 // console.log(JSON.stringify(cates))
7 // console.log(cates)
8})();COPY
https://github.com/Innei/Back-End-Study/blob/master/express-demo/db.js