i have transection and purchase collections,which is contaning transection and purchase details now i want to convert it into single collection. based on transectionid we need to combine the documents
Below is my transection collection data's
{
"transectionid": "1",
"transectionamount": "2000",
"transectiondate": "2016-07-12 19:22:28",
},
{
"transectionid": "2",
"transectionamount": "1000",
"transectiondate": "2016-07-12 20:17:11",
}
below is my purchase collection datas
{
"purchaseid": "1",
"transectionid": "1",
"itemprice": "1200",
"itemcode": "edcvb",
"itemquantity": "1",
},
{
"purchaseid": "2",
"transectionid": "1",
"itemprice": "800",
"itemcode": "dfgh",
"itemquantity": "2",
},
{
"purchaseid": "3",
"transectionid": "2",
"itemprice": "1000",
"itemcode": "zxcvb",
"itemquantity": "1",
}
my expectation result : this is how order collecion should store {
"transectionid" : "1",
"transectionamount": "2000",
"transectiondate": "2016-07-12 19:22:28",
"items" : [
{
"purchaseid": "1",
"itemprice":"1200",
"itemcode": "edcvb",
"itemquantity": "1",
},
{
"purchaseid": "2",
"itemprice": "800",
"itemcode": "dfgh",
"itemquantity": "2",
}
]
}
{
"transectionid" : "2",
"transectionamount": "1000",
"transectiondate": "2016-07-12 20:17:11",
"items" : [
{
"purchaseid": "3",
"itemprice":"1000",
"itemcode": "zxcvb",
"itemquantity": "1",
}
]
}
well using javascript and just some for cycles you can do this.
var transactionsSize = transactions.length;
var purchasesSize = purchases.length
var finalArray = JSON.parse(JSON.stringify(transactions));
for(var i = 0 ; i < transactionsSize; i++ ) {
for(var j = 0; j < purchasesSize; j++) {
if(transactions[i].transactionid == purchases[j].transactionid) {
if(!finalArray[i].items) {
finalArray[i].items = [];
finalArray[i].items.push(purchases[j]);
} else {
finalArray[i].items.push(purchases[j]);
}
}
}
}
here is a working fiddle(note that some names are not the same as your input'transections' for example) https://jsfiddle.net/yph9yc86/1/
If you are using native mongo driver, you need to implement it yourself.
If you are using mongoose, take a look at population, and even cross DB population, as they already did all the work.
For example, according to your schemas:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var transactionSchema = Schema({
transectiondate: Date,
transectionid : Number,
transectionamount: Number,
items: [{ type: Number, ref: 'Item' }]
});
var itemSchema = Schema({
transectionid: Number,
purchaseid : Number,
itemprice: Number,
itemcode: String,
itemquantity: Number,
});
var Transaction = mongoose.model('Transaction', transactionSchema);
var Item = mongoose.model('Item', itemSchema);
Transaction
.find({})
.populate('items')
.exec(function (err, transactinos) {
console.log(transactinos);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With