【问题标题】:How to join three collections in mongodb?如何在mongodb中加入三个集合?
【发布时间】:2021-04-06 19:46:30
【问题描述】:

我正在使用几乎纯 JS 代码来连接 MongoDB 中的三个集合,我相信必须有一种更简单的方法来做到这一点,只需使用 mongoose 查询。

这是我的情况;我有一个可以创建和销售文件的卖家。我希望我的卖家能够看到他出售的文件。

这是我的 Order 集合架构:

const OrderSchema = new mongoose.Schema({
    //...
    
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User',
        required: true
    },
    documents: [
        {
            document: {
                type: mongoose.Schema.ObjectId,
                ref: 'Document',
                required: true
            },
            price: {
                type: Number,
                required: [true, 'Price is required']
            }
        }
    ],
    
    //...
});

我的文档架构如下所示:

const DocumentSchema = new mongoose.Schema({
    //...
    
    title: {
        type: String,
        required: [true, 'Please provide a title'],
    },
    author: {
        type: mongoose.Schema.ObjectId,
        ref: 'Seller',
        required: true
    },
    
    //...
});

正如我之前所说,我想获得一份属于已售出的已登录卖家的文档列表。 (类似这样)。

"data": [
        {
            "orderId": "606b448dd2d9d643a811bc33",
            "documentId": "606b448dd2d9d643a811bc34",
            "title": "Document 1 u1",
            "price": 90,
            "createdAt": "2021-04-05T17:10:37.469Z"
        },
        {
            "orderId": "606b43d2cd9b2740b8b8974b",
            "documentId": "606b43d2cd9b2740b8b8974c",
            "title": "Business Affiliate u7",
            "price": 222,
            "createdAt": "2021-04-05T17:07:30.859Z"
        },
        {
            "orderId": "606b1a03ec048e0d44cb3bee",
            "documentId": "606b1a03ec048e0d44cb3bef",
            "title": "Business Affiliate u7",
            "price": 777,
            "createdAt": "2021-04-05T14:09:07.539Z"
        },
        {
            "orderId": "606b1a03ec048e0d44cb3bee",
            "documentId": "606b1a03ec048e0d44cb3bf0",
            "title": "Doc 1 u1",
            "price": 1,
            "createdAt": "2021-04-05T14:09:07.539Z"
        },
 ]

到目前为止,我得到的代码是下面的代码。它看起来有点丑,它包含三个 Fors。

const documents = await Document.find().where('author', req.uid).select('orders').populate({ path: 'orders' })

    let filteredOrders = [];

    for (const document of documents) {
        //GET ALL ORDERS THAT CONTAINS THIS DOCUMENTS
        const orders = await Order.find().where('documents.document', document._id).populate({ path: 'documents.document', select: 'title' }).sort('-createdAt');

        for (const order of orders) {
            for (const doc of order.documents) {
                if (doc.document._id.toString() == document._id.toString()) {
                    filteredOrders.push({
                        orderId: order._id,
                        documentId: doc._id,
                        title: doc.document.title,
                        price: doc.price,
                        createdAt: order.createdAt
                    });
                }
            }
        }
    }

    filteredOrders.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

    res.status(200).json({ success: true, data: filteredOrders });

有没有办法只使用 Mongoose 可以获得相同的结果?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    经过一些研究和阅读文档(20 个标签),这是最终代码(可能需要一些清理):

    let id = mongoose.Types.ObjectId(req.uid);
    
        const orders = await Order
            .aggregate([
                { $unwind: '$documents' },
                {
                    $lookup: {
                        from: "documents",
                        localField: "documents.document",
                        foreignField: "_id",
                        as: "document"
                    }
                },
                { $match: { 'document.author': id } },
                { $project: { user: 1, deliveryEmail: 1, createdAt: 1, documentTitle: '$document.title', documentId: '$documents.document', documentPrice: '$documents.price' } },
                { $sort: { 'createdAt': -1 } }
            ])
    
        res.status(200).json({ success: true, data: orders });

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2021-11-04
      • 2020-09-03
      • 2022-01-01
      • 2012-09-15
      • 2012-04-04
      • 2018-06-23
      • 2018-03-06
      • 2021-11-22
      相关资源
      最近更新 更多