通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
- 使用id对集合进行关联;
- 使用
populate
方法进行关联集合查询;
一、使用id对集合进行关联
通过将关联字段的类型指定为mongoose.Schema.Types.ObjectId
// 用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
// 文章集合规则
const postSchema = new mongoose.Schema({
title: {
type: String
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
});
// 用户集合
const User = mongoose.model("User", userSchema);
// 文章集合
const Post = mongoose.model("Post", postSchema);
二、使用populate
方法进行关联集合查询
Post.find()
.populate("author")
.then(result => console.log(result));
写在最后
如果你感觉文章不咋地
//(ㄒoㄒ)//
,就在评论处留言,作者继续改进;o_O???
如果你觉得该文章有一点点用处,可以给作者点个赞;\\*^o^*//
如果你想要和作者一起进步,可以微信扫描二维码,关注前端老L;~~~///(^v^)\\\~~~
谢谢各位读者们啦(^_^)∠※
!!!