I would like to build a JSON structure as below
{
"employee": {
"hireDate": "01/01/2000",
"serviceDate": "01/01/2000",
"employeeDetails": [
{
"roleName": "Analyst",
"beginDate": "01/01/2000",
"endDate": "12/31/2001",
"status": "Active"
},
{
"roleName": "Developer",
"beginDate": "01/01/2002",
"endDate": "01/01/2021",
"status": "Active"
}
],
"name": [
{
"firstName": "Jason",
"lastName": "Washington"
}
]
}
}
I'm have individual objects information as seperate resultsets from DB2 SQL. I would like to form/ build a JSON structure
Here i use one common key name as employer_id in all table result so it will easy to map all result as per employer id
let employee_details =[{
"employer_id":1,
"roleName": "Analyst",
"beginDate": "01/01/2000",
"endDate": "12/31/2001",
"status": "Active"
},{
"employer_id":1,
"roleName": "Developer",
"beginDate": "01/01/2002",
"endDate": "01/01/2021",
"status": "Active"
}
]
let employee_personal_details =[{
"employer_id":1,
"firstName": "Jason",
"lastName": "Washington"
}]
let employee_work_details = [{
"employer_id":1,
"hireDate": "01/01/2000",
"serviceDate": "01/01/2000"
}]
let employee = employee_work_details.map(details=>{
return {
...details,
employeeDetails: employee_details.filter(_details => _details.employer_id == details.employer_id),
name: employee_personal_details.filter( personal_details => personal_details.employer_id == details.employer_id)
}
})
console.log({employee})
You can use map and reduce to build an array from multiple input arrays.
We match based on some shared id, in this case employeeId.
You could make this behaviour more sophisticated by specifying a join property for each array, let's say name or date of birth.
const employees = [{ id: 1, name: "Mark Ryan" }, { id: 2, name: "Joe Smith" }, { id: 3, name: "Meg Green" }];
const employeeDetails = [{ employeeId: 1, roleName: "Analyst", beginDate: "01/01/2002" }, { employeeId: 1, roleName: "Developer", beginDate: "01/01/2005" }, { employeeId: 2, roleName: "QA", beginDate: "03/05/2015" }, { employeeId: 3, roleName: "Manager",beginDate: "11/08/2010" }];
const contactDetails = [{ employeeId: 1, email: "mark.ryan#example.com" }, { employeeId: 2, phone: "555-009" }, { employeeId: 2, email: "joe.smith#example.com" }, { employeeId: 3, email: "meg.ryan#example.com" }];
const arraysToJoin = [ { employeeDetails } , { contactDetails } ];
const result = employees.map(employee => {
return arraysToJoin.reduce( (acc, obj) => {
acc[Object.keys(obj)[0]] = Object.values(obj)[0].filter(details => acc.id === details.employeeId).map(details => {
const { employeeId, ...rest } = details;
return rest;
});
return acc;
}, employee);
});
console.log("Result:",result);
Related
I want to get the data only when all the query matches.
here is the query to get the data:
exports.getParkingListByCriteria = async (req, res) => {
const cityQuery = req.body.city;
const stateQuery = req.body.state;
const countryQuery = req.body.country;
try {
const filter = await Parking.find({
$and: [
{
"location.city": { $regex: new RegExp(cityQuery, ($options = "i")), //I want to apply date filter here },
"location.state": {
$regex: new RegExp(stateQuery, ($options = "i")),
},
"location.country": {
$regex: new RegExp(countryQuery, ($options = "i")),
},
},
],
});
res.status(200).send(filter);
} catch (error) {
return res.status(500).json({ error: error.message });
}
};
Date is stored inside of the parking table where it shows the availability of the parking details for that date and time
availability: [
{
date: {
type: Date,
},
day: {
type: String,
},
startTime: {
type: Date,
},
endTime: {
type: Date,
},
},
],
collection from the database:
{"_id": {"$oid": "62cc46e920782c4be0673d50"},
"merchantId": {"$oid": 62c950ebc96c2b690028be8b"},
"contactInfo": {"name": "Ronda Green", "phoneNumber": 9104933588},
"about": "Laborum non minim ad",
"location":
{"address": "349 scott avenue",
"city": "edmund",
"state": "louisiana",
"zipCode": 49755,
"country": "australia"},
"price": 18,
"parkingType": "parkingLot",
"parkingInfo": [{"parkingName": "College Place","_id":"$oid":"62cc46e920782c4be0673d51"},"default": []}],
"totalSpots": [168],
"parkingSpotType": ["Motorbike","Large"],
"coordinates":
{"lng": 1.522645,
"lat": 125.939061},
"status": "active",
"isFeePaid": false,
**"availability": [
date: "2022-07-10"
startTime: "7:00"
endTime:"22:00"
_id: 62cd048559e9a786ff1df9d7],**
"specialEvents": [],
"__v": 0}
I want to show data only when both city criteria and date criteria matches.
The question is not very clear. If you want to get the totalSpots for each matching document, you can use a simple find with a projection:
db.collection.find(
{
"location.city": {$regex: "edmund", $options: "i"},
"availability.date": "2022-07-10"
},
{
totalSpots: 1
})
See how it works on the playground example
If you want something else, please provide the requested results
This question already has answers here:
Mongoose/Mongodb: Exclude fields from populated query data
(4 answers)
Closed 2 years ago.
I just not want to pass user id in discussion array.
Now I getting back from this route like this.
{
"_id": "5f4600ab7ec81f6c20f8608d",
"name": "2",
"category": "2",
"description": "2",
"deadline": "2020-08-10",
"discussion": [
{
"date": "2020-09-03T06:12:15.881Z",
"_id": "5f5089bd265ec85b896f8491",
"user": {
"_id": "5f5089a2265ec85b896f848f",
"userName": "MdJahidHasan01"
},
"text": "3"
},
{
"date": "2020-09-03T06:12:15.881Z",
"_id": "5f5089ae265ec85b896f8490",
"user": {
"_id": "5f5089a2265ec85b896f848f",
"userName": "MdJahidHasan01"
},
"text": "2"
}
]
}
But I want to get like this
{
"_id": "5f4600ab7ec81f6c20f8608d",
"name": "2",
"category": "2",
"description": "2",
"deadline": "2020-08-10",
"discussion": [
{
"date": "2020-09-03T06:12:15.881Z",
"_id": "5f5089bd265ec85b896f8491",
"user": {
"userName": "MdJahidHasan01"
},
"text": "3"
},
{
"date": "2020-09-03T06:12:15.881Z",
"_id": "5f5089ae265ec85b896f8490",
"user": {
"userName": "MdJahidHasan01"
},
"text": "2"
}
]
}
Select does not working here. I just not want to pass user id in discussion array just username.
As I use user id for authorization. So it is not an good idea to send user id.
Project Model
const mongoose = require('mongoose');
const projectSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
category: {
type: String,
require: true
},
description: {
type: String,
require: true
},
deadline: {
type: String,
require: true
},
discussion: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
date: {
type: Date,
default: Date.now()
},
text: {
type: String,
require: true
}
}
]
});
module.exports = mongoose.model('Project', projectSchema);
Project Details Route
router.get('/:projectId',async (req, res) => {
try {
const project = await Project.findById(req.params.projectId)
.populate('discussion.user', 'userName')
.select('-discussion.user._id')
console.log(project);
await res.status(200).json(project);
} catch (error) {
console.log(error);
return res.status(400).json({ 'error': 'Server Error' });
}
})
Just add this after the .populate:
delete project.discussion._id
I have two schemas: 'Leads' and 'LeadsCategory'.
Leads Schema:
const id = mongoose.Schema.Types.ObjectId;
const leadsSchema = mongoose.Schema(
{
_id: id,
userId: { type: id, ref: "User", required: true },
leadName: String,
leads: [
{
_id: id,
name: String,
mobile: Number,
address: String,
education: {
school: String,
graduation: String
},
leadType: { type: id, ref: "LeadsCategory", required: true }
}
]
},
{
timestamps: true
}
);
module.exports = mongoose.model("lead", leadsSchema);
Leads Category Schema:
const id = mongoose.Schema.Types.ObjectId;
const leadsCategorySchema = mongoose.Schema({
_id: id,
name: {
type: String,
required: true
},
leadsData: [{ type: id, ref: 'lead' }]
},
{ timestamps: true }
);
module.exports = mongoose.model("LeadsCategory", leadsCategorySchema);
I'm referencing the leadsCategory as soon as new lead is created and it does populate my leadsCategory into the Leads controller.
So my final data inside 'Leads collection' looks like this:
[
{
"_id": "5e8832dde5d8273824d86502",
"leadName": "Freshers",
"leads": [
{
"education": {
"school": "LPS",
"graduation": "some school"
},
"location": {
"state": "delhi",
"country": "india"
},
"name": "Joey",
"mobile": 1524524678,
"_id": "5e8832dde5d8273824d86500",
"leadType": {
"_id": "5e88285f5dda5321bcc045a6",
"name": "all"
}
},
{
"education": {
"school": "DAV",
"graduation": "some school"
},
"location": {
"state": "delhi",
"country": "india"
},
"name": "Ben",
"mobile": 1524524678,
"_id": "5e8832dde5d8273824d86501",
"leadType": {
"_id": "5e88285f5dda5321bcc045a6",
"name": "all"
}
}
]
}
]
But now I need to associate the leads data into my 'leadsCategory' collection so that I can query the leads data according to the leadType created. For now, I have only one 'leadType':'all'. But further, I will create more types and populate the data accordingly.
I tried something like this:
exports.get_leads_type_all = (req, res) => {
LeadsCategory.find()
.populate('leadsData')
.then( data => {
res.json(data)
})
}
But this returns me only empty array like this:
{ "leadsData": [],
"_id": "5e88285f5dda5321bcc045a6",
"name": "all",
"createdAt": "2020-04-04T06:25:35.171Z",
"updatedAt": "2020-04-04T06:25:35.171Z",
"__v": 0
},
Please help me to associate and related this data. I have tried lot's of thins but could not make it work.
try this:
exports.get_leads_type_all = (req, res) => {
LeadsCategory.find()
.populate('leadsData')
.execPopulate()
.then( data => {
res.json(data)
})
}
https://mongoosejs.com/docs/api/document.html#document_Document-execPopulate
I need to find the element by id, then go into the array of objects, find the desired by id and add the field guessId into it and insert the id key into it and assign the array of id. How can I do that ?
https://jsoneditoronline.org/?id=442f1dae0b2d4997ac69d44614e55aa6
In general, I need to create a GuessId field with such a structure
in fact, I am doing the voting, that is, the key in guessId will be go to vote, and the array to it, this is users who vote
{
"_id": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"bio": {
"firstname": "Лена",
"lastname": "фыв",
"middlename": "",
"company": "вв"
},
"files": [
{
"_id": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6",
"destination": "./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"filename": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
"path": "uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
"folder": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"info": {
"size": 20805727,
"mimetype": "audio/mp3",
"encoding": "7bit",
"originalname": "Ахуевший Ленусик (Банк русский стандарт). Выпуск #5..mp3",
"fieldname": "selectedFile"
},
"userId": "5e05da745b21e61ccc84a892",
"date": "2019-12-27T10:19:12.213Z"
},
{
"_id": "81b94dea-ece6-421c-b68a-0aa59332cd0d",
"destination": "./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"filename": "81b94dea-ece6-421c-b68a-0aa59332cd0d.mp3",
"path": "uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\81b94dea-ece6-421c-b68a-0aa59332cd0d.mp3",
"folder": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"info": {
"size": 13515683,
"mimetype": "audio/mp3",
"encoding": "7bit",
"originalname": "Выпуск #75 Попрошайка НСВ..mp3",
"fieldname": "selectedFile"
},
"userId": "5e05da745b21e61ccc84a892",
"date": "2019-12-27T10:25:37.710Z"
}
],
"date": "2019-12-27T10:19:12.213Z",
"__v": 1
}
Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const HabalkaSchema = new Schema({
_id: {
type: String
},
bio: {
firstname: String,
lastname: String,
middlename: String,
company: String
},
files: [
{
_id: {
type: String
},
destination: {
type: String
},
filename: {
type: String
},
path: {
type: String
},
folder: {
type: String
},
info: {
size: {
type: Number
},
mimetype: {
type: String
},
encoding: {
type: String
},
originalname: {
type: String
},
fieldname: {
type: String
},
},
date: {
type: Date,
default: Date.now
},
bio: {
type: Object
},
userId: String,
guessId: {},
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Habalka = mongoose.model('habalka', HabalkaSchema);
You can use the positional $ operator like this:
router.put("/habalka/:id/:fileId/:guessId", async (req, res) => {
const result = await Habalka.findOneAndUpdate(
{
_id: req.params.id,
"files._id": req.params.fileId
},
{
"files.$.guessId": {
[req.params.guessId]: ["a", "b"] //todo: get this array from req.body
}
},
{
new: true
}
);
res.send(result);
});
Route url: http://..../habalka/f58482b1-ae3a-4d8a-b53b-ede80fe1e225/2e4e40c7-4df6-4974-8d16-bb24cd8134d6/asda2
This will give you a result like this in the given file:
"files": [
{
"info": {
"size": 20805727,
"mimetype": "audio/mp3",
"encoding": "7bit",
"originalname": "Ахуевший Ленусик (Банк русский стандарт). Выпуск #5..mp3",
"fieldname": "selectedFile"
},
"date": "2019-12-27T10:19:12.213Z",
"_id": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6",
"destination": "./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"filename": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
"path": "uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
"folder": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
"userId": "5e05da745b21e61ccc84a892",
"guessId": {
"asda2": [
"a",
"b"
]
}
},
And later if you want to add an item inside one of the guessId arrays, you can use the following code:
router.put("/habalka/:id/:fileId/:guessId", async (req, res) => {
const result = await Habalka.findOneAndUpdate(
{
_id: req.params.id,
"files._id": req.params.fileId
},
{ $push: { [`files.$.guessId.${req.params.guessId}`]: "c" } },
{
new: true
}
);
res.send(result);
});
I'm pretty new to Mongoose and MongoDB in general so I'm having a difficult time figuring out if something like this is possible:
I'm trying to filter only those document who has created_by_id not [].
This is schema.
var CampaignSchema = new Schema({
name: { type: String, required: true },
description: { type: String, required: true },
budget: { type: String, required: true },
tags: { type: [ String ], required: true },
status: { type: Number },
payment_id: { type: String },
created_by_id: [{ type: Schema.Types.ObjectId, ref: 'User' }],
attached_file: {
uploaded_on: { type: Date, default: Date.now },
uploaded_by: { type: String, required: true },
},
added_url: {
added_on: { type: Date, default: Date.now },
added_by: { type: String, required: true },
},
updated_by: { type: String },
created_on: { type: Date, default: Date.now },
updated_on: { type: Date }
});
This is code:
_getCampaigns(req, res){
var token = helpersMethods.getToken(req.headers);
var page = parseInt(req.query.page) || 0; //for next page pass 1 here
var limit = parseInt(req.query.limit) || 10;
var term = new RegExp(req.query.search, 'i');
var obj = { "created_by_id": { "$ne": [] } };
if (token) {
Campaign.find(obj)
.populate({
path : 'created_by_id',
match : {
$or: [
{ name: { $regex: term }},
]
}
})
.sort({ updateAt: -1 })
.skip(page * limit)
.limit(limit)
.exec((err, doc) => {
if (err) {
return res.json(err);
}
Campaign.count(obj).exec((count_error, count) => {
if (err) {
return res.json(count_error);
}
return res.json({
total: count,
page: page,
pageSize: doc.length,
campaigns: doc
});
});
});
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
}
And i'm getting postman output like this, but i do not want the object who don't have created_by_id array:
{
"total": 2,
"page": 0,
"pageSize": 2,
"campaigns": [
{
"attached_file": {
"uploaded_by": "Demo user",
"uploaded_on": "2019-01-29T11:07:27.475Z"
},
"added_url": {
"added_by": "Demo user",
"added_on": "2019-01-29T11:07:27.475Z"
},
"tags": [
"tag1",
"tags2"
],
"_id": "5c5033ef28f63c72808f2225",
"created_by_id": {
"_id": "5c4965d477e7191c4d40b412",
"name": "Demo user",
"email": "demo#arth.tech",
"phone": "9918XXXXXX",
"type": "1",
"admin_rights": "1",
"password": "$2a$10$6T2ulNN60fBG9/vFgf8XhetkcWb/2zDxGXUMXMRi2Bltn8s1NEkbq",
"__v": 0,
"createdAt": "2019-01-24T07:31:03.327Z",
"loggedIn_at": "2019-01-30T06:33:04.388Z",
"loggedOut_at": "2019-01-24T08:03:44.091Z"
},
"name": "Test Campaign",
"description": "Discription of test campaign",
"budget": "2000",
"updated_by": "Demo User",
"created_on": "2019-01-29T11:07:27.475Z",
"__v": 0
},
{
"attached_file": {
"uploaded_by": "Demo User",
"uploaded_on": "2019-01-29T13:08:48.021Z"
},
"added_url": {
"added_by": "Demo user",
"added_on": "2019-01-29T13:08:48.021Z"
},
"tags": [
"test1",
"test2"
],
"_id": "5c505060b97f871123d97990",
"created_by_id": [],
"name": "Hello Campaign",
"description": "Description of Hello campaign",
"budget": "1000",
"updated_by": "Hello user",
"created_on": "2019-01-29T13:08:48.021Z",
"__v": 0
}
]
}
I want only those objects who has created_by_id, the actual output i want.
{
"total": 1,
"page": 0,
"pageSize": 1,
"campaigns": [
{
"attached_file": {
"uploaded_by": "Demo user",
"uploaded_on": "2019-01-29T11:07:27.475Z"
},
"added_url": {
"added_by": "Demo user",
"added_on": "2019-01-29T11:07:27.475Z"
},
"tags": [
"tag1",
"tags2"
],
"_id": "5c5033ef28f63c72808f2225",
"created_by_id": {
"_id": "5c4965d477e7191c4d40b412",
"name": "Demo user",
"email": "demo#arth.tech",
"phone": "9918XXXXXX",
"type": "1",
"admin_rights": "1",
"password": "$2a$10$6T2ulNN60fBG9/vFgf8XhetkcWb/2zDxGXUMXMRi2Bltn8s1NEkbq",
"__v": 0,
"createdAt": "2019-01-24T07:31:03.327Z",
"loggedIn_at": "2019-01-30T06:33:04.388Z",
"loggedOut_at": "2019-01-24T08:03:44.091Z"
},
"name": "Test Campaign",
"description": "Discription of test campaign",
"budget": "2000",
"updated_by": "Demo User",
"created_on": "2019-01-29T11:07:27.475Z",
"__v": 0
}
]
}
can any one help?
I did , what i want. here is updated code.
_getCampaigns(req, res){
var token = helpersMethods.getToken(req.headers);
var page = parseInt(req.query.page) || 0; //for next page pass 1 here
var limit = parseInt(req.query.limit) || 10;
var term = new RegExp(req.query.search, 'i');
var obj = {};
if (token) {
Campaign.find(obj)
.populate({
path : 'created_by_id',
match : {
$or: [
{ name: { $regex: term }},
]
}
})
.sort({ updateAt: -1 })
.skip(page * limit)
.limit(limit)
.exec((err, docs) => {
if (err) {
return res.json(err);
}else{
docs = docs.filter(function(doc) {
return doc.created_by_id.length != 0;
});
Campaign.count(obj).exec((count_error, count) => {
if (err) {
return res.json(count_error);
}else{
return res.json({
total: count,
page: page,
pageSize: docs.length,
campaigns: docs
});
}
});
}
});
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
}