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?
Related
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
}
});
});
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);
const mongoose = require('mongoose');
const addressSchema = mongoose.Schema({
type: String,
street: String,
city: String,
state: String,
country: String,
postalcode: Number
});
const createStudentSchema = mongoose.Schema({
admisionnum: Number,
first: String,
last: String,
phone: String,
address : [addressSchema],
isActive : { type : Boolean, default: true}
}, {
timestamps: true
});
module.exports = mongoose.model('createStudent', createStudentSchema);
Addreschema for address in array of objects . I am getting null in the output for the json below .
This is json input
{
"admisionnum":"1",
"first": "Dan",
"last": "HEllo",
"phone": "9000909575",
"address" : [
{
"type": "own",
"street": "18 ksdhks",
"city": "chennai",
"state": "Tamil Nadhu",
"country": "India",
"postalcode": "600097"
}
],
"isActive": "true"
}
Response Json output
{
"isActive": true,
"_id": "5c9e57f718e3de2ca4dd1d86",
"admisionnum": 1,
"first": "Jesus",
"last": "christ",
"phone": "9000909575",
"address": [
null,
null,
null,
null,
null,
null
],
"createdAt": "2019-03-29T17:37:59.291Z",
"updatedAt": "2019-03-29T17:37:59.291Z",
"__v": 0
}
Please help how to bind data for address . controller code is below
exports.createStudent = (req, res) => {
// Create a Note
const CreateStudent = new createStudent({
admisionnum: req.body.admisionnum,
first: req.body.first,
last: req.body.last,
phone: req.body.phone,
address : [
req.body.address.type,
req.body.address.street,
req.body.address.city,
req.body.address.state,
req.body.address.country,
req.body.address.postalcode
] ,
isActive: req.body.type
});
// Save Note in the database
CreateStudent.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the Note."
});
});
};
Just use address : req.body.address, and it should work fine.
Since your address is an array and you are sending address array as well in the request, you don't need to do anything else.
Try this:
const CreateStudent = new createStudent({
admisionnum: req.body.admisionnum,
first: req.body.first,
last: req.body.last,
phone: req.body.phone,
address : req.body.address ,
isActive: req.body.type
});
I have following model
var reservationSchema = new Schema({
lcode: Number,
reserved_days: [daySchema],
});
var daySchema = new Schema({
pk: Number,
date: String,
price: Number,
payment_type: String,
payment_date: String,
room: { room_id: String, name: String }
});
I have a reservation with array of reserved_days. I need to compare this reservation and reservations in database and find reservation where at least one reserved_days date or reserved_days room.room_id are the same that contains in array. Array must not be fully equal, I just need to find duplicate days.
Now I try the following
Reservation.find({
$or: [{
"reserved_days.room.room_id": {
$in: req.body.reservation.reserved_days
}
}, {
"reserved_days.date": {
$in: req.body.reservation.reserved_days
}
}]
}).exec(function(err, found)
but it doesn't work.
Test request reservation.reserved_days object looks the following
"reserved_days": [
{
"pk": 3543,
"date": "2018-07-14",
"price": 3213.0,
"payment_type": "Безналичный расчет",
"payment_date": "2017-12-28",
"room": {
"room_id": "7",
"name": "Стандарт"
}
},
{
"pk": 3544,
"date": "2018-07-15",
"price": 3213.0,
"payment_type": "Безналичный расчет",
"payment_date": "2017-12-28",
"room": {
"room_id": "7",
"name": "Стандарт"
}
}]
Is it possible to do ?