Here is my json data, I want to insert multiple travels information in travelers. Total numbers of travels may be given by the user.
In the below format I can just add one traveler.
return amadeus.booking.flightOrders.post(
JSON.stringify({
'data':{
'type': 'flight-order',
'flightOffers': [response.data.flightOffers[0]],
'travelers':[{
"id": 1,
"name": {
"firstName": req.body.firstname,
"lastName": req.body.lastname
},
"gender": req.body.gender,
"contact": {
"emailAddress": req.body.emailaddress,
"phones": [{
"deviceType": req.body.devicetype,
"countryCallingCode": req.body.countrycallingcode,
"number": req.body.number
}]
},
"documents": [{
"documentType": req.body.documentype,
"birthPlace": req.body.birthplace,
"issuanceLocation": req.body.issuancelocation,
"issuanceDate": req.body.issuancedate,
"number": req.body.p_number,
"expiryDate": req.body.expirydate,
"issuanceCountry": req.body.issuancecountry,
"validityCountry": req.body.validitycountry,
"nationality": req.body.nationality,
"holder": true
}]
}]
}
})
);
}).then(function (response)
travelers is an array. You can push multiple entries to it like
data.travelers.push(traveler);
You can run get multiple traveler details in your API like:
{
"travelers": [{
"firstname": "John",
"secondname": "Doe",
}, {
"firstname": "Jane",
"secondname": "Doe",
}]
}
This can then be looped over to push multiple travelers in the data variable.
let id = 1;
req.body.travelers.forEach(traveler => {
data.travelers.push({
id: id++,
name: {
firstName: traveler.firstname,
lastName: traveler.lastname
}
});
});
Related
I need to replace members array data with new array of objects mems given below.
{
"name": "Test Group",
"members": [{
'userId': {
$oid: 'fjkfkffy'
},
name: 'Himanshu'
}],
"athletes": [],
"leads": []
}
Here I want to replace members array of object with new array of objects. I basically need to overwrite that members array. I've been trying to do something like this below, but I got an error. Can anyone please help me out?
const mems = [{
"user": {
"$oid": "6093a4a709cc0b000d31ber8",
},
"role": "manager"
},
{
"user": {
"$oid": "60a3aea6ecbf4398f01aa598"
},
"role": "user"
}
];
entities.findOneAndUpdate({
_id: ObjectID(entityID),
"groups._id": ObjectID(groupID)
}, {
$set: {
'groups.$.name': name,
'groups.$.members': mems
}
}, {
'new': true
});
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
The Json below is returned from this method
const ByTheId = await this.service.GetById(ID);
I want to access the Owner properties, I tried to get
ByTheId.Owner._id
But that didnt work
{
"_id": "5eb905426564556758754",
"PhysicalId": "023546757986",
"SerialNumber": "serial-65867546712345587",
"Owner": {
"_id": "5ecbxderw9gf6dct4833a54",
"firstname": "John",
"lastname": "Doe",
"email": "john#doe.com",
"phonenumber": "887-8789-878",
"address": "007 John Street",
"lga": "Shira",
"state": "State"
}
}
schema
Owner: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'User'
},
method
async GetById(Id: any): Promise<DTO> {
return await this.Model.findById(Id).populate('Owner', {
_id: 1,
firstname: 1,
lastname: 1,
email: 1,
phonenumber: 1,
address: 1,
state: 1,
lga: 1,
});
}
Those are the properties I want it to return from owner object
How can I access the id property of the owner?
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 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);