MongoDB - Как я могу найти все другие связанные документы из всех коллекций. У меня есть доступ только к 1 идентификатору - PullRequest
1 голос
/ 06 апреля 2020

Здравствуйте. Я использую mon goose для поиска похожих записей в моей коллекции.

/*Product model*/

    const productSchema = mongoose.Schema(
      {
        writer: {
          type: Schema.Types.ObjectId,
          ref: "User",
        },
        title: {
          type: String,
          maxlength: 50,
        },
        description: {
          type: String,
        },
        Category: {
          type: String,
          default: "Mobiles",
        }
    );

У меня может быть доступ только к одному идентификатору за раз, я хочу иметь доступ к все остальные сообщения

, которые имеют общую строку в названии, описании или категории.

В параметрах у меня есть только Product _id.

Это мой код.

router.post("/MultiCards/:any", (req, res) => {
  let order = req.body.order ? req.body.order : "desc";
  let sortBy = req.body.sortBy ? req.body.sortBy : "_id";
  let limit = req.body.limit ? parseInt(req.body.limit) : 100;

  Product.find({ _id: req.params.any })
    .sort([[sortBy, order]])
    .limit(limit)
    .exec((err, products) => {
      if (err) return res.status(400).json({ success: false, err });
      res
        .status(200)
        .json({ success: true, products, postSize: products.length });
    });
});

1 Ответ

2 голосов
/ 06 апреля 2020

Если у вас действительно есть доступ только к _id продукта, найдите этот продукт, а затем используйте возвращенный объект для поиска похожих продуктов с помощью find

router.post("/MultiCards/:any", (req, res) => {
  let order = req.body.order ? req.body.order : "desc";
  let sortBy = req.body.sortBy ? req.body.sortBy : "_id";
  let limit = req.body.limit ? parseInt(req.body.limit) : 100;

  Product.findById(req.params.any)
    .sort([[sortBy, order]])
    .limit(limit)
    .exec((err, product) => {
      if (err) return res.status(400).json({ success: false, err });
      Product.find({ Category: product.Category}).then((products) => {
       res
        .status(200)
        .json({ success: true, products, postSize: products.length });
      })

    });
});

ES2016 Версия

router.post('/MultiCards/:any', async (req, res) => {
  const order = req.body.order ? req.body.order : 'desc';
  const sortBy = req.body.sortBy ? req.body.sortBy : '_id';
  const limit = req.body.limit ? parseInt(req.body.limit) : 100;
  try {
    const product = await Product.findById(req.params.any).sort([[sortBy, order]])
      .limit(limit).exec();
    const products = await Product.find({ title: `/${product.title}/i` });
    res
      .status(200)
      .json({ success: true, products, postSize: products.length });
  } catch (error) {
    res.status(400).json({ success: false, error });
  }

Если вы хотите подобное, сделайте запрос, подобный этому /query/i

, как написано в понедельник goose документы

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
...