在mongodb中搜索多个集合

时间:2019-05-19 12:32:43

标签: javascript mongodb express

我有两个收藏集,电影和表演。

const ShowsSchema = new Schema({
title: {
 type: String,
 required: true
       },
description: {
 type: String,
 required: true
},
image: {
 type: String,
 required: true
})

目前,我只能从一个集合中搜索数据,但我想从两个集合中获取数据。在浏览了网站上的一些解决方案之后,我遇到了$ lookup字段。

 router.get('/:query', (req, res, next) => {
  const query = req.params.query;
  Show.aggregate([{

   $lookup: {
    from: "Movies",
    localField: "title",
    foreignField: "title",
    as: "movies"
     }
  }], () => {

  Show.find({
  title: {
    $regex: new RegExp(query),
    $options: "$i"
  },

}, (err, shows) => {
  if (err) {
    console.error(err);
  }
  res.json(shows);
  });
 });
});

我被困在这里,将不胜感激。

1 个答案:

答案 0 :(得分:0)

router.get('/:query', (req, res, next) => {
   const query = req.params.query;
   Show.aggregate([{
       $match : {
        title: {
            $regex: new RegExp(query),
            $options: "$i"
        }
      }
   },{
      $lookup: {
         from: "Movies",
         localField: "title",
         foreignField: "title",
         as: "movies"
      }
   }],(err, shows) => {
     if (err) {
         console.error(err);
     }
     res.json(shows);
   });
 });

希望这对您有所帮助。

相关问题