@veteral

Как в mongodb сформировать результат на основании двух коллекций?

Здравствуйте!
Есть две коллекции
objects:
const ObjectSchema = new Schema({
   _id: { type: ObjectId, required: true },
    name: { type: String, required: true },
    address: { type: String, required: true },
    passwords: { type: String, required: true },
    telefone: { type: String },
    device: { type: String },
    control: { type: Boolean, default: false },
});

defects:
const DefectSchema = new Schema({
    _id: { type: ObjectId, required: true },
    objectId: { type: ObjectId, ref: "Object" },
    train: { type: String, required: true },
    date: { type: Date, required: true },
    time: { type: String, required: true },
    causeId: { type: ObjectId, ref: "Cause" },
});

Надо.
1. Отфильтровать defects по date
2. Сформировать json используя предыдущий результат:
{
name,
address,
defects: [...]
}
  • Вопрос задан
  • 31 просмотр
Пригласить эксперта
Ответы на вопрос 1
@veteral Автор вопроса
Попробовал так:
const def = await Defect
        .find(
            {date: 
                {
                    $gte: new Date("2021-03-17T06:04:57.972+00:00"), 
                    $lte: new Date("2021-04-17T06:04:57.972+00:00")
                }
            }
            );              

    const defects = await Object.aggregate([       
        {
            $lookup: {
              from: "def",
              localField: "_id",
              foreignField: "objectId",
              as: "d",
            },
          },        
    ])

Почему то выдает массив нулевой:
[
    {
        "_id": "607a688c1ee975025413bcea",
        "control": false,
        "passwords": "1",
        "name": "name1",
        "address": "address1",
        "__v": 0,
        "d": []
    }
]
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы