生于理想

导航

集合关联

多集合联合查询(集合关联)

通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log(err, '数据库连接失败'));
//创建集合规则
//用户集合规则
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);
//创建用户
// User.create({ name: '张三' })
//     .then(result => console.log(result))
//创建文章,将作者id绑定到文章
// Post.create({ title: '123', author: '6329aa1549fa849539463833' })
//     .then(result =>  console.log(result));
Post.find().populate('author').then(result => console.log(result))

 

posted on 2022-09-20 20:06  生于理想  阅读(46)  评论(0)    收藏  举报