码迷,mamicode.com
首页 > 数据库 > 详细

数据库集合关联

时间:2019-07-26 19:33:58      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:god   console   bsp   cti   object   关联   pes   err   schema   

// 引入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值关联

数据库集合关联

标签:god   console   bsp   cti   object   关联   pes   err   schema   

原文地址:https://www.cnblogs.com/treasurea/p/11251973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!