javascript - How to get data from MongoDB to simple array using Node.JS and Mongoose? -
let's mongodb schema:
var shopschema = new mongoose.schema({ nameshop: string, products: [ { type: mongoose.schema.types.objectid, ref: 'product' }] }); var productschema = new mongoose.schema({ nameproduct: string, fruits: [ { type: mongoose.schema.types.objectid, ref: 'fruit' } ] }); var fruitschema = new mongoose.schema({ namefruit: string, price: number }); module.exports = { shop: mongoose.model('shop', shopschema), product: mongoose.model('product', productschema), fruit: mongoose.model('fruit', fruitschema) }
i know can data in way, result of code "ugly" array
var schema = require('../model/schema'); schema.shop.find({}).populate({ path: 'products', model: 'product', populate: { path: 'fruits', model: 'fruit' } }).exec(callback);
is possible data schema in way have nice array? e.g.:
var myarray = [ { nameshop: "tesco", nameproduct: "new", namefruit: "apple", price: 10 }, { nameshop: "tesco", nameproduct: "new", namefruit: "pinapple", price: 4 }, { nameshop: "eko", nameproduct: "old", namefruit: "kiwi", price: 8 }, { nameshop: "makro", nameproduct: "fresh", namefruit: "pear", price: 7 }, { nameshop: "carefour", nameproduct: "new", namefruit: "orange", price: 6 } ];
you go aggregation framework route, has capacity flatten arrays through $unwind
operator. generate new record each , every element of list data field on unwind applied. flattens data.
after flattening data require $lookup
operator "join" on products
field products
collection. repeat process nested fruits schema.
lets see example (untested) understand 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: above untested code serves guide making couple of assumptions running code in test environment latest mongodb , mongoose versions support $lookup
operator , can perform same aggregation query in mongo shell.
Comments
Post a Comment