$ lookup работает в MongoDB, но не работает с mongoose - PullRequest
0 голосов
/ 10 октября 2018

У меня есть два документа:

Category = new Schema({
  storeKey: { type: String, required: true },
  cod: { type: String, required: true },
  name: { type: String, required: true },
  visible: { type: Boolean }
},
  {
    timestamps: {
      createdAt: "created",
      updatedAt: "updated"
    }
  }

);

и:

Product = new Schema({
        name: { type: String, required: true },
        cod: String,
        storeKey: { type: String, required: true },
        categoryId: String,
        description: { type: String, required: true },
        price: { type: Number, required: true },
        stockQuantity: { type: Number, required: true },
        avatar: String,
        visible: Boolean
    }, {
            timestamps: true
        });

Запрос на сервере с mongoose для поиска продуктов с категорией агрегирования

Product.aggregate([
        {
            $lookup: {
                from: "Category",
                localField: "categoryId",
                foreignField: "_id",
                as: "category"
            }
        }]
    ).exec((error, done) => {
        if (error) res.status(500).send({
            message: langs[req.query.lang],
            error
        });

        res.status(200).send(done);
    });

запросна локальном терминале

db.Product.aggregate(
        [{
            $lookup: {
                localField: "categoryId",
                from: "Category",
                foreignField: "_id",
                as: "category"
            }
        }])

В терминале $ lookup работает правильно.С мангустом, он приносит дубликаты записей и не приносит существующие категории.Что не так?

1 Ответ

0 голосов
/ 10 октября 2018

@ Энтони Уинзлет был прав, должно быть categories (в пуральном) должно было оставить categories (в пуральном), а не category, но я также не определил поле categoryId какObjectId в схеме продукта, поэтому он сравнивал строку с ObjectId.В тестах в терминале я сохранил возврат сервера, который возвращает поля _id в виде строк.Теперь это работает. Спасибо!

const ProductSchema = new Schema({
    name: { type: String, required: true },
    cod: String,
    storeKey: { type: String, required: true },
    categoryId: { type: Schema.Types.ObjectId, ref: 'categories' },
    description: { type: String, required: true },
    price: { type: Number, required: true },
    stockQuantity: { type: Number, required: true },
    avatar: String,
    visible: Boolean
}, {
        timestamps: true
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...