constmongoose=require('mongoose');mongoose.connect('mongodb://localhost:27017/mongo-relation',{useNewUrlParser:true,useUnifiedTopology:true},err=>{if(err){控制台.log('数据库连接失败');}console.log('数据库连接成功');})constcategorySchema=newmongoose.Schema({name:{type:String}},{toJSON:{virtuals:true}});categorySchema.virtual('posts',{//本地键localField:'_id',//关联模型ref:'Post',//外键foreignField:'categories',//输出多个justOne:false});constCategory=mongoose.model('Category',categorySchema);constpostSchema=newmongoose.Schema({title:{type:String},body:{type:String},类别:{type:mongoose.SchemaTypes.ObjectId,ref:'Category'},categories:[{type:mongoose.SchemaTypes.ObjectId,ref:'Category'}]});constPost=mongoose.model('Post',postSchema);异步函数init(){//constcats=awaitCategory.find().populate('类别');//控制台日志(猫);//[//{_id:5ee0a7f22adf1624e8b9b64d,name:'nodejs',__v:0},//{_id:5ee0a7f22adf1624e8b9b64e,name:'vue.js',__v:0}//]//加上lean()//constcats=awaitCategory.find().populate('posts').lean();//控制台日志(猫);//[//{//_id:5ee0a7f22adf1624e8b9b64d,//name:'nodejs',//__v:0,//posts:[[Object]]//},//{//_id:5ee0a7f22adf1624e8b9b64e,//name:'vue.js',//__v:0,//posts:[[Object],[Object]]//}//]//cats[0].posts查看第1个分类内容//constcats=awaitCategory.find().populate('posts').lean();//console.log(cats[0].posts);//[//{//_id:5ee0a74dc6a921238454fa52,//title:'第2篇文章',//body:'内容2',//__v:9,//category:5ee0a7f22adf1624e8b9b64d,//类别:[5ee0a7f22adf1624e8b9b64d,5ee0a7f22adf1624e8b9b64e]//}//]//JSON.stringifyconstcats=awaitCategory.find().populate('posts').lean();控制台日志(JSON.stringify(猫));//[{"_id":"5ee0a7f22adf1624e8b9b64d","name":"nodejs","__v":0,//"posts":[{"_id":"5ee0a74dc6a921238454fa52",//"title":"第2篇文章","body":"内容2","__v":9,//"类别":"5ee0a7f22adf1624e8b9b64d",//"类别":["5ee0a7f22adf1624e8b9b64d","5ee0a7f22adf1624e8b9b64e"]}]},//{"_id":"5ee0a7f22adf1624e8b9b64e","name":"vue.js","__v":0,"posts":[{"_id":"5ee0a74dc6a921238454fa51","title":"第1篇文章","body":"内容1","__v":5,"category":"5ee0a7f22adf1624e8b9b64d","categories":["5ee0a7f22adf1624e8b9b64e"]},{"_id":"5ee0a74dc6a921238454fa52","title":"第2篇文章","body":"内容2","__v":9,"category":"5ee0a7f22adf1624e8b9b64d","categories":["5ee0a7f22adf1624e8b9b64d","5ee0a7f22adf1624e8b9b64e"]}]}]//等待发布。插入Many([{//title:'Section1',//body:'Content1'//},{//title:'Section2',//body:'Content2'//}]);//awaitCategory.insertMany([{//名称:'nodejs'//},//{//名称:'vue.js'//}//]);//constcategory=awaitCategory.find();//控制台日志(类别);//constcat1=awaitCategory.findOne({name:'nodejs'});//constcat2=awaitCategory.findOne({name:'vue.js'});//constpost1=awaitPost.findOne({title:'Part1sentence'});//constpost2=awaitPost.findOne({title:'Part2sentence'});posts.category//console.log(cat1);//post1.categories=[cat2];//post2.categories=[cat1,cat2];//等待post1.save();//等待post2.save();//constpost=awaitPost.find();//控制台日志(发布);//console.log(post1,post2);//constpost=awaitPost.find().populate('categories')//console.log(post[0],post[1]);}init()
