mongoose populate关联一个对象数组里的某个属性字段

mongoose populate关联一个对象数组里的某个属性字段

schema↓

var articleSchema = new mongoose.Schema({
    title:String,//文章标题
    type:{
        type:mongoose.Schema.Types.ObjectId,//关联类型集合
        ref:'types'
    },//文章类型
    author:{
        type:mongoose.Schema.Types.ObjectId,//关联用户集合
        ref: 'users'
    },//作者
    read:{
        type:Number,
        default:0
    },//被阅读数量
    discuss:[//评论存放到文章的id上,是个数组,但是这个数组上有用户评论的与户名id,需要把用户名id转为正常的名字
        {
            time:Number,
            msg:String,
            name:{
                type:mongoose.Schema.Types.ObjectId,//关联用户集合
                ref: 'users'
            }
        }
    ],//评论
    del:{
        type:Boolean,
        type:false
    }//是否已经删除
});

接口获取↓

router.get('/discuss1', (req, res) => {
    try {
        let id = req.query.id;
        if (id == '' || id == undefined) {
            return res.json({
                code: 1,
                msg: '参数不全'
            })
        }
        articleMode.findOne({
            _id:req.query.id
        }, {
            __: 0
        //populate中参数1:数组名.属性;参数2:绑定另个表中的关键字(我那个表有username关键字)
        }).populate('discuss.name','username').then((data) => {
            res.json({
                code: 0,
                data:data.discuss
            })
        })
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})

postmain测试截图

搬砖地址:https://developer.aliyun.com/ask/80923?spm=a2c6h.13159736

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值