egg(29)--mongoose使用聚合管道多表关联查询
db.js
var mongoose = require('mongoose'); mongoose.connect('mongodb://eggadmin:[email protected]:27017/eggcms',{ useNewUrlParser: true },function(err){ if(err){ console.log(err) return } console.log("数据库连接成功") }) module.exports = mongoose;
articlecate.js
var mongoose = require('./db.js'); var ArticleCateSchema = mongoose.Schema({ title:{ type:String, unique:true }, description:String, addtime:{ type:Date, default:Date.now } }) var ArticleCateSchema = mongoose.model('ArticleCate',ArticleCateSchema,'articleCate'); module.exports = ArticleCateSchema
user.js
var mongoose = require('./db.js'); var UserSchema = mongoose.Schema({ username:{ type:String, unique:true }, password:String, name:String, age:Number, tel:Number, status:{ type:Number, default:1 } }) var UserSchema = mongoose.model('User',UserSchema,'user'); module.exports = UserSchema
article.js
var mongoose = require('./db.js'); var ArticleSchema = mongoose.Schema({ title:{ type:String, unique:true }, cid:{//分类id type:mongoose.Types.ObjectId }, author_id:{//用户id type:mongoose.Types.ObjectId }, author_name:{ type:String }, description:String, content:String }) var ArticleSchema = mongoose.model('Article',ArticleSchema,'article'); module.exports = ArticleSchema
新增数据
app.js
var mongoose = require("mongoose") var ArticleCateModel = require('./articlecate.js'); var ArticleModel = require('./article.js'); var UserModel = require('./user.js'); var cate = new ArticleCateModel({ title:"广东新闻", description:"广东新闻" }) cate.save() var user = new UserModel({ username:"lishi", password:"123456", name:"李四", age:20, tel:13737241111 }) user.save() var article = new ArticleModel({ // title:"习访问美国", title:"广东新闻发生大火", // cid:"5c00d3dcceb92704e4d30248", //国际 cid:"5c00d400a7998c2a885ab9ba", //国内 // author_id:"5c00d46fb004c9247c6f90ca", //张三 cid:"5c00d82bf252ca209c90facb", author_id:"5c00d47be5fcb430b0cbf290", //李四 // 5c00d47be5fcb430b0cbf290,李四 // author_name:"张三", author_name:"李四", description:"东莞发生大火........", content:"东莞发生大火........" }) article.save()
查询数据
app.js
var ArticleModel = require('./article.js'); ArticleModel.aggregate([{ $lookup: { from: 'articleCate', localField: "cid", foreignField: "_id", as: "cate" } }, { $lookup: { from: 'user', localField: "author_id", foreignField: "_id", as: "user" } }], function (err, docs) { if (err) { console.log(err); return; } console.log(JSON.stringify(docs)) })
相关推荐
80530895 2020-07-05
mkhhxxttxs 2020-06-14
80500495 2020-06-14
86211943 2020-03-01
80530895 2020-02-23
80500495 2020-01-29
86211943 2020-01-24
lovecodeblog 2020-01-24
87261046 2019-12-23
86211943 2019-12-20
lightlanguage 2019-12-16
MYRENZHIBO 2019-08-28
85234656 2018-09-03
fudirong 2012-04-12
80500495 2019-07-01