通过mongo

时间:2018-04-20 22:47:35

标签: javascript arrays node.js mongodb mongoose

我想通过填充字段查询。在这种情况下,填充的字段是评论。因此,如果我的搜索查询与评论表描述字段匹配...则返回该书。评论是一系列对象,描述是其中的关键之一。

我尝试在查询对象中使用评论[0] .description但它没有用。

getBookInfo: (req, res) => {
        const search = req.params.search;
        const query = { $or: [{ title: { $regex: search, $options: 'i' } }] };
        Books.find(query).populate('reviews').exec(function(err, books) {
            if (err) {
                return err;
            }
            return books;
        });
    }

1 个答案:

答案 0 :(得分:0)

您想要搜索图书并填充与您的查询匹配的评论。

所以documentation你有权使用match来填充人口。

你走了:

getBookInfo: async (req, res) => {
  try {
    const search = req.params.search;

    // query for books matching by condition
    const query = { 
      $or: [
        { title: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
      ] 
    };

    // include reviews matching by conditions
    const include = {
      path: 'reviews',
      match: {
        description: { 
          $regex: search, 
          $options: 'i' 
        }
      },
      options: {limit: 5}
    };

    const books = await Books
                          .find(query)
                          .populate(include)
                          .lean();
    res.status(200).send(books);
  }
  catch (error) {
    res.status(500).send(error);
  }
};

更新:

据我所知您想查询评论和预订。

  1. 在Review模型中有book字段,该字段会保留图书_idtitledescription
  2. 当用户添加评论时,只需将该图书数据放入评论文档。
  3. 查询直接评论集合。
相关问题