请问前辈们这样的连表要怎么操作

//文章
let articalSchema = new mongoose.Schema({
    title: String,
    author: {
        type:mongoose.Schema.Types.ObjectId,
        ref:'user'
    },
    tag:[{
        tid:{
            type:mongoose.Schema.Types.ObjectId,
            ref:'tag'
        }
    }],
    status:Boolean,
    comment:[{
        cid:{
            type:mongoose.Schema.Types.ObjectId,
            ref:'comment'
        }
    }]
})

let commentSchema = new mongoose.Schema({
    comment:String,
    from_uid:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'user'
    }
})

let userSchema = new mongoose.Schema({
    name:String
})

能一次性的把文章下面的comment里的from_uid关联的user表的内容查出来吗

阅读 1.5k
1 个回答

populate,下面是示例代码

const mongoose = require('mongoose');
(async function () {
  mongoose.connect('mongodb://localhost/test', { useUnifiedTopology: true, useNewUrlParser: true })
  const Artical = mongoose.model('Artical', new mongoose.Schema({
    title: String,
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
  }), 'test_artical')
  const Comment = mongoose.model('Comment', new mongoose.Schema({
    content: String,
    user: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
  }), 'test_ comment')
  const User = mongoose.model('User', new mongoose.Schema({
    username: String,
  }), 'test_user')
  await Artical.deleteMany({})
  await Comment.deleteMany({})
  await User.deleteMany({})
  // 填充测试数据
  const user = await new User({ username: '嘎嘎' }).save()
  const artical = await new Artical({ title: '钢铁是这样练成的' }).save()
  const comment = await new Comment({ content: '十五字十五字十五字十五字十五字', user }).save()
  artical.comments.push(comment)
  await artical.save()
  // 查询
  console.log(JSON.stringify(
    await Artical.find({}).populate({ path: 'comments', populate: { path: 'user' } })
  ))
  mongoose.disconnect()
}()).catch(err => {
  console.error(err)
  mongoose.disconnect()
})

输出结果:

[
  {
    "comments": [
      {
        "user": [
          {
            "_id": "5deda9fcfec029546434bfbf",
            "username": "嘎嘎",
            "__v": 0
          }
        ],
        "_id": "5deda9fcfec029546434bfc1",
        "content": "十五字十五字十五字十五字十五字",
        "__v": 0
      }
    ],
    "_id": "5deda9fcfec029546434bfc0",
    "title": "钢铁是这样练成的",
    "__v": 1
  }
]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题