数据库集合关联

Posted treasurea

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据库集合关联相关的知识,希望对你有一定的参考价值。

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require(‘mongoose‘);
// 数据库连接
mongoose.connect(‘mongodb://localhost/wrj‘,  useNewUrlParser: true)
    // 连接成功
    .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: ‘itheima‘).then(result => console.log(result));
// 创建文章
// Post.create(titile: ‘123‘, author: ‘5c0caae2c4e4081c28439791‘).then(result => console.log(result));
Post.find().populate(‘author‘).then(result => console.log(result))

输出一个对象 包含上面注释的作者的id值 和 title及title值 及_v

 

 

此例以博客文章的发表为例 因为在数据库中id值是独一无二的 作者在发表文章时 数据库会自动产生一个id值  将作者信息 与其发表的文章 通过id值关联

以上是关于数据库集合关联的主要内容,如果未能解决你的问题,请参考以下文章

Android ORMLite ForeignCollection关联外部集合

关联规则1

Laravel 5.1 从原始数据库(或只是一个数组)创建集合或关联数组

MongoDB 集合关联

[JM_06]JMeter之集合点、关联-操作解析

在表/集合视图控制器及其关联的 diffable 数据源子类之间共享数据模型的好方法是啥?