const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true }).then(() => console.log('数据库连接成功')).catch(err => console.log(err, '数据库连接失败'))
const userSchema = new mongoose.Schema({name: {type: String,required: true}
});
const postSchema = new mongoose.Schema({titie: {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: 'geyao' }).then(result => console.log(result)) */
/* Post.create({ titie: '123', author: '5ebe6d2fe4235b14b4424558' }).then(result => console.log(result)) */
Post.create({ titile: '123', author: '5ebe9383aec3f03ec885764c' }).then(result => console.log(result))/* Post.find().populate('author').then(result => console.log(result)) */
运行结果