I'm trying to 'unwind' columns from an included table of a query, but i'm not getting it right, I've tried the following solution:
Remove 'included' Table Name from response - Sequelize
Unsucessfully
So far I'm able to create the following query:
include: {
model: Branches,
as: 'userBranches',
include: {
model: Countries,
as: 'branchCountry',
attributes: ['countryName'],
},
},
}),
Getting the following:
"data": [
{
"id": "758406e2-47ce-4f1e-b4be-492103ee2f91",
"whatsappNumber": "5531975080415",
"whatsappId": "5531975080415",
"businessName": "Quintal da Dirce",
"cnpj": "123456789",
"email": "lepcbelisario#gmail.com",
"ownerFirstName": "Leandro",
"ownerMiddleName": "Parisi",
"ownerLastName": "Carvalho",
"ownerCpf": "123456789",
"password": "123456789",
"botName": "Walle",
"logo": null,
"isActive": true,
"createdAt": "2021-06-26T21:52:03.330Z",
"updatedAt": "2021-06-26T21:52:03.330Z",
"userBranches": [
{
"id": "f7488e1d-5fc4-4314-b7bd-f500e6b77c3f",
"userId": "758406e2-47ce-4f1e-b4be-492103ee2f91",
"managerName": "Leandro",
"branchName": "Quintal da Dirce 2000",
"countryId": 1,
"stateId": 1,
"cityId": 1,
"neibourhood": "Minha Kombi",
"street": "rua da kombui",
"streetNumber": "222",
"streetComplement": "222",
"postalCode": "12345",
"isActive": true,
"createdAt": "2021-06-26T21:52:03.347Z",
"updatedAt": "2021-06-26T21:52:03.347Z",
"branchCountry": {
"countryName": "Brazil"
}
},
But i would like to get:
"data": [
{
"id": "758406e2-47ce-4f1e-b4be-492103ee2f91",
"whatsappNumber": "5531975080415",
"whatsappId": "5531975080415",
"businessName": "Quintal da Dirce",
"cnpj": "123456789",
"email": "lepcbelisario#gmail.com",
"ownerFirstName": "Leandro",
"ownerMiddleName": "Parisi",
"ownerLastName": "Carvalho",
"ownerCpf": "123456789",
"password": "123456789",
"botName": "Walle",
"logo": null,
"isActive": true,
"createdAt": "2021-06-26T21:52:03.330Z",
"updatedAt": "2021-06-26T21:52:03.330Z",
"userBranches": [
{
"id": "f7488e1d-5fc4-4314-b7bd-f500e6b77c3f",
"userId": "758406e2-47ce-4f1e-b4be-492103ee2f91",
"managerName": "Leandro",
"branchName": "Quintal da Dirce 2000",
**"countryName": "Brazil"**
"stateId": 1,
"cityId": 1,
"neibourhood": "Minha Kombi",
"street": "rua da kombui",
"streetNumber": "222",
"streetComplement": "222",
"postalCode": "12345",
"isActive": true,
"createdAt": "2021-06-26T21:52:03.347Z",
"updatedAt": "2021-06-26T21:52:03.347Z",
},
Any tips?
Related
How do i a write a query that will copy the phoneNumber from data.accounts.contact.phone.phoneNumber to data.phoneNumber in jsonb postgres.
I tried this command
UPDATE customer."user" SET domain = jsonb_set(domain,'{phoneNumber}', text('domain' ->'accounts'-> 0 -> 'contacts' -> 'phone' -> 'phoneNumber'))
but got this error
Error: HINT: Could not choose a best candidate operator. You might need to add explicit type casts.
SQL state: 42725
Character: 1913
{
"id": "87b31b1f-5dae-4506-8099-9812fa1633eb",
"gender": "F",
"status": "VERIFIED",
"lastName": "Lawal",
"password": "T3m1t0p3",
"username": "aminat2#gmail.com",
"firstName": "Aminat",
"phoneNumber": "",
"accounts": [
{
"status": "IN_REVIEW",
"contact": {
"phone": { "phoneNumber": "7809284029", "diallingCode": "+44" },
"address": { "city": "London", "address": "42 Sark Walk", "country": "United Kingdom", "postcode": "E163PS" },
"emailAddress": "aminat2#gmail.com"
},
"location": {
"id": "4a110b1f-9319-4282-b645-81ea71b53e04",
"status": "ACTIVE",
"currency": {
"id": "1",
"to": false,
"date": "2021-09-19T16:45:33",
"from": true,
"buyFxRate": "1",
"sellFxRate": "1",
"
},
"diallingCode": "+44",
"locationLabel": "United Kingdom",
"
"modifiedDateTime": "2021-09-19T16:45:33",
},
}
],
}
I'm making an API Rest with node, express, typescript and mongoose. I have a method GET that return this result:
{
"success": true,
"status": 200,
"message": "categories listed",
"data": [
{
"_id": "612650e55fe1ce0de138e2af",
"products": [
{
"_id": "612650e55fe1ce0de138e2b0",
"productID": {
"reviews": [
"611e61ba8cb43f7454787ebb",
"611e62008cb43f7454787ebc"
],
"_id": "610b18f3e2244a187b36f2d7",
"title": "PS4",
"description": "La mejor consola del mercado del mundo, mundial",
"photo": "https://amazon-clone-jparrot.s3.amazonaws.com/1628123519052",
"price": 400,
"stockQuantity": 23,
"__v": 0,
"category": "60fc6454b68717acc239cc6a",
"owner": "610b9ed8763da4308223aae0",
"averageRating": null,
"id": "610b18f3e2244a187b36f2d7"
},
"quantity": 1,
"price": 400
}
],
"owner": {
"_id": "611d2d39dfcc705972c1ccb8",
"name": "Jaume",
"email": "jaumeparrot2#gmail.com",
"password": "$2a$10$Rv9Rzrff6578feCdDjyeKuarKCSHYRqKp5n5wTi2IWtcLBOupvPgu",
"__v": 0,
"address": "611e9ccdf47c7a7a9cb1d5d9"
},
"estimatedDelivery": "Wednesday September 1st",
"__v": 0
}
]
}
The problem is that I need to retrieve the object "owner", that is, I need to recover this json:
{
"success": true,
"status": 200,
"message": "categories listed",
"data": [
{
"_id": "612650e55fe1ce0de138e2af",
"products": [
{
"_id": "612650e55fe1ce0de138e2b0",
"productID": {
"reviews": [
"611e61ba8cb43f7454787ebb",
"611e62008cb43f7454787ebc"
],
"_id": "610b18f3e2244a187b36f2d7",
"title": "PS4",
"description": "La mejor consola del mercado del mundo, mundial",
"photo": "https://amazon-clone-jparrot.s3.amazonaws.com/1628123519052",
"price": 400,
"stockQuantity": 23,
"__v": 0,
"category": "60fc6454b68717acc239cc6a",
"owner": {
"_id": "611d2d39dfcc705972c1ccb8",
"name": "Jaume",
"about": "My na is Jaume",
"__v": 0
},
"averageRating": null,
"id": "610b18f3e2244a187b36f2d7"
},
"quantity": 1,
"price": 400
}
],
"owner": {
"_id": "611d2d39dfcc705972c1ccb8",
"name": "Jaume",
"email": "jaumeparrot2#gmail.com",
"password": "$2a$10$Rv9Rzrff6578feCdDjyeKuarKCSHYRqKp5n5wTi2IWtcLBOupvPgu",
"__v": 0,
"address": "611e9ccdf47c7a7a9cb1d5d9"
},
"estimatedDelivery": "Wednesday September 1st",
"__v": 0
}
]
}
For generate this JSON, I'm using this method:
https://github.com/jparrot92/amazon-clone-back/blob/master/src/controllers/order.ts
To retrieve you should use data.owner. This will give owner details as object.
This is the solution:
const products = await Order.find({ owner: req.user._id })
.populate('owner')
.populate({
path: 'products.productID',
populate: {
path: 'owner',
model: 'Owner',
},
})
.exec();
For our collection which looks like this:
> db.companies.find().limit(1).pretty() {
"_id": ObjectId("52cdef7c4bab8bd675297d8b"),
"name": "AdventNet",
"permalink": "abc3",
"crunchbase_url": "http://www.crunchbase.com/company/adventnet",
"homepage_url": "http://adventnet.com",
"blog_url": "",
"blog_feed_url": "",
"twitter_username": "manageengine",
"category_code": "enterprise",
"number_of_employees": 600,
"founded_year": 1996,
"deadpooled_year": 2,
"tag_list": "",
"alias_list": "Zoho ManageEngine ",
"email_address": "pr#adventnet.com",
"phone_number": "925-924-9500",
"description": "Server Management Software",
"created_at": ISODate("2007-05-25T19:24:22Z"),
"updated_at": "Wed Oct 31 18:26:09 UTC 2012",
"overview": "<p>AdventNet is now <a href=\"/company/zoho-manageengine\"
title=\"Zoho ManageEngine\" rel=\"nofollow\">Zoho ManageEngine</a>.</p>\n\n<p>F
ounded in 1996, AdventNet has served a diverse range of enterprise IT, networkin
g and telecom customers.</p>\n\n<p>AdventNet supplies server and network managem
ent software.</p>",
"image": {
"available_sizes": [
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-150
x150.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-250
x250.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-450
x450.png"
]
]
},
"products": [],
"relationships": [{
"is_past": true,
"title": "CEO and Co-Founder",
"person": {
"first_name": "Sridhar",
"last_name": "Vembu",
"permalink": "sridhar-vembu"
}
}, {
"is_past": true,
"title": "VP of Business Dev",
"person": {
"first_name": "Neil",
"last_name": "Butani",
"permalink": "neil-butani"
}
}, {
"is_past": true,
"title": "Usabiliy Engineer",
"person": {
"first_name": "Bharath",
"last_name": "Balasubramanian",
"permalink": "bharath-balasibramanian"
}
}, {
"is_past": true,
"title": "Director of Engineering",
"person": {
"first_name": "Rajendran",
"last_name": "Dandapani",
"permalink": "rajendran-dandapani"
}
}, {
"is_past": true,
"title": "Market Analyst",
"person": {
"first_name": "Aravind",
"last_name": "Natarajan",
"permalink": "aravind-natarajan"
}
}, {
"is_past": true,
"title": "Director of Product Management",
"person": {
"first_name": "Hyther",
"last_name": "Nizam",
"permalink": "hyther-nizam"
}
}, {
"is_past": true,
"title": "Western Regional OEM Sales Manager",
"person": {
"first_name": "Ian",
"last_name": "Wenig",
"permalink": "ian-wenig"
}
}],
"competitions": [],
"providerships": [{
"title": "DHFH",
"is_past": true,
"provider": {
"name": "A Small Orange",
"permalink": "a-small-orange"
}
}],
"total_money_raised": "$0",
"funding_rounds": [],
"investments": [],
"acquisition": null,
"acquisitions": [],
"offices": [{
"description": "Headquarters",
"address1": "4900 Hopyard Rd.",
"address2": "Suite 310",
"zip_code": "94588",
"city": "Pleasanton",
"state_code": "CA",
"country_code": "USA",
"latitude": 37.692934,
"longitude": -121.904945
}],
"milestones": [],
"video_embeds": [],
"screenshots": [{
"available_sizes": [
[
[
150,
94
],
"assets/images/resized/0004/3400/43400v1
-max-150x150.png"
],
[
[
250,
156
],
"assets/images/resized/0004/3400/43400v1
-max-250x250.png"
],
[
[
450,
282
],
"assets/images/resized/0004/3400/43400v1
-max-450x450.png"
]
],
"attribution": null
}],
"external_links": [],
"partners": []
} >
For the below query for our node.js app.
db.companies.aggregate([{
$match: {
"name": "Facebook"
},
$project: {
"_id": 0,
"name": 1,
"people": "$relationships.person.last_name"
}
}])
Gives the following error:
assert: command failed: {
"ok" : 0,
"errmsg" : "A pipeline stage specification object must contain exactly o ne field.",
"code" : 16435 } : aggregate failed
_getErrorWithCode#src/mongo/shell/utils.js:25:13 doassert#src/mongo/shell/assert.js:13:14
assert.commandWorked#src/mongo/shell/assert.js:267:5
DBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5
#(shell):1:1
2016-09-17T19:20:26.303+0530 E QUERY [thread1] Error: command
failed: {
"ok" : 0,
"errmsg" : "A pipeline stage specification object must contain exactly o ne field.",
"code" : 16435 } : aggregate failed :
_getErrorWithCode#src/mongo/shell/utils.js:25:13 doassert#src/mongo/shell/assert.js:13:14
assert.commandWorked#src/mongo/shell/assert.js:267:5
DBCollection.prototype.aggregate#src/mongo/shell/collection.js:1312:5
#(shell):1:1
I'm unable to figure out why?
You are missing some braces for your aggregation pipeline operators. The correct pipeline should be:
db.companies.aggregate([
{ "$match": { "name": "Facebook" } }, /* match pipeline stage */
{ "$project": { /* project pipeline stage */
"_id": 0,
"name": 1,
"people": "$relationships.person.last_name"
} }
])
Is it possible to search using the associated table but excluding the data in the associated table?
E.g.
db.Bill.findAll({
include: [{
model: self.db.Group,
where: {
id: groupId
},
include: [{
model: self.db.Account,
where: {username: username}
}]
}]
});
Currently, I get these results...
[
{
"id": 2,
"title": "Title",
"category": "OTHERS",
"currency": "php",
"recurring": false,
"date_from": null,
"date_to": null,
"createdAt": "2015-08-12T10:54:08.000Z",
"updatedAt": "2015-08-12T10:54:08.000Z",
"group_id": 2,
"Group": {
"id": 2,
"name": "Group",
"createdAt": "2015-08-12T10:54:07.000Z",
"updatedAt": "2015-08-12T10:54:07.000Z",
"Account": {
"username": "username"
}
}
}
]
I want to find all the bills under a group but I only want the results to be
[
{
"id": 2,
"title": "Title",
"category": "OTHERS",
"currency": "php",
"recurring": false,
"date_from": null,
"date_to": null,
"createdAt": "2015-08-12T10:54:08.000Z",
"updatedAt": "2015-08-12T10:54:08.000Z",
"group_id": 2
}
];
i need to find record matching userId. the userId can be in any level of document.
It can be in parent level or it can be inside friends array.
[{
"_id": "543357620c9af6066e689713",
"createdDate": "2014-10-06 08:00 pm",
"cancle": false,
"eventDate": "2014/12/12",
"eventstatus": true,
"location": "chennai",
"userId": "54334def7e85de48638d1069",
"createdBy": "four",
"eventName": "jamba",
"__v": 0,
"friends": []
},
{
"_id": "543356fe0c9af6066e68970c",
"createdDate": "2014-10-06 07:59 pm",
"cancle": false,
"eventDate": "2014/12/12",
"eventstatus": true,
"location": "chennai",
"userId": "54310801e2659ecc3650100b",
"createdBy": "one",
"eventName": "tea ",
"__v": 0,
"friends": [
{
"userId": "54310814e2659ecc3650100c",
"userName": "two",
"phoneNumber": "22222222"
},
{
"userId": "54310945e2659ecc3650100d",
"userName": "three",
"phoneNumber": "33333333"
},
{
"userId": "54334def7e85de48638d1069",
"userName": "four",
"phoneNumber": "44444444"
}
]
}]
i am trying for long time. Any help is highly appreciated.
You need the $or operator. Also, you don't need to iterate to query for elements within an array. Assuming your collection is named Events:
Events.find({
$or: [
{ _id: req.params.userId },
{ 'friends.userId': req.params.userId }
]
}).exec();