Skip to content Skip to sidebar Skip to footer

How To Get Data From Mongodb To Simple Array Using Node.js And Mongoose?

Let's say this is my MongoDB schema: var shopSchema = new mongoose.Schema({ nameShop: String, products: [ { type: mongoose.Schema.Ty

Solution 1:

You could go the aggregation framework route, which has the capacity to flatten the arrays through the $unwind operator. This will generate a new record for each and every element of the list data field on which unwind is applied. It basically flattens the data.

After flattening the data you would require the $lookup operator to do a "join" on the products field to the products collection. Repeat the process for the nested fruits schema.

Lets see an example (untested) to understand this better

var Schema = require('../model/schema');
Schema.Shop.aggregate([
    { "$unwind": "$products" },
    {
        "$lookup": {
            "from": "products",
            "localField": "products",
            "foreignField": "_id",
            "as": "product"
        }
    },
    { "$unwind": "$product" },
    { "$unwind": "$product.fruits" },
    {
        "$lookup": {
            "from": "fruits",
            "localField": "product.fruits",
            "foreignField": "_id",
            "as": "fruits"
        }
    },  
    {
        "$project": {
            "nameShop": 1,
            "nameProduct": "$product.nameProduct",
            "nameFruit": "$fruits.nameFruit",
            "price": "$fruits.price",
        }
    }
]).exec(function (err, result){
    if (err) throw err;
    console.log(result);
})

DISCLAIMER: The above is untested code which only serves as a guide by making a couple of assumptions that you are running the code in a test environment with the latest MongoDB and mongoose versions that support the $lookup operator AND that you can perform the same aggregation query in mongo shell.

Post a Comment for "How To Get Data From Mongodb To Simple Array Using Node.js And Mongoose?"