V
V
veteral2021-04-17 12:56:40
Mongoose
veteral, 2021-04-17 12:56:40

How to form a result based on two collections in mongodb?

Hello!
There are two collections of
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" },
});

Necessary.
1. Filter defects by date
2. Generate json using previous result:
{
name,
address,
defects: [...]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
veteral, 2021-04-17
@veteral

Tried like this:

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",
            },
          },        
    ])

For some reason it gives an array of zero:
[
    {
        "_id": "607a688c1ee975025413bcea",
        "control": false,
        "passwords": "1",
        "name": "name1",
        "address": "address1",
        "__v": 0,
        "d": []
    }
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question