【问题标题】:Search multiple collections in mongodb在 mongodb 中搜索多个集合
【发布时间】:2019-05-20 09:14:00
【问题描述】:

我有两个合集,电影和节目。

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);
  });
 });
});

我被困在这里,任何帮助将不胜感激。

【问题讨论】:

  • 用电影架构更新问题!

标签: javascript mongodb express


【解决方案1】:
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);
   });
 });

希望这有帮助!

【讨论】:

    猜你喜欢
    • 2013-12-02
    • 2021-04-17
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多