I want when a category is deleted. All its child categories and its own categories will be deleted.
For example, I want if the web development category is deleted. All its child categories (delete Django and Django Channel)
{
"statusCode": 200,
"data": {
"categories": [
{
"_id": "62fdfb567bb46dcf93b3717f",
"title": "Web development",
"parent": null,
"position": "important",
"slug": "-eb-development",
"createdAt": "2022-08-18T08:41:58.826Z",
"updatedAt": "2022-08-18T08:41:58.826Z",
"children": [
{
"_id": "62fdfb677bb46dcf93b3718d",
"title": "Django",
"parent": "62fdfb567bb46dcf93b3717f",
"position": "unimportant",
"slug": "-jango",
"createdAt": "2022-08-18T08:42:15.557Z",
"updatedAt": "2022-08-18T08:42:15.557Z",
"children": [
{
"_id": "62fdfb857bb46dcf93b371a1",
"title": "Django chennels",
"parent": "62fdfb677bb46dcf93b3718d",
"position": "unimportant",
"slug": "-jango-chennels",
"createdAt": "2022-08-18T08:42:45.665Z",
"updatedAt": "2022-08-18T08:42:45.665Z",
"children": [],
"id": "62fdfb857bb46dcf93b371a1"
}
],
"id": "62fdfb677bb46dcf93b3718d"
}
],
"id": "62fdfb567bb46dcf93b3717f"
}
]
}
}
I wrote a code for this which does not work properly and removes only one child from the desired category.
const category = await this.checkExistCategory(id);
const deleteResult = await Category.deleteMany({
$or: [{ _id: category._id }, { parent: category._id }],
});
Thank you very much for helping me!!
Related
I want to join more than two collections in MongoDB . Is it possible to join?
I have 2 collections and I want to join them based by their ids
news collection
{
"lang": "ru",
"news": [{
"title": "title",
"content": "desc",
"image": "path",
"categoryId": {
"$oid": "6171499e0ba3d75082823c9a"
},
"createdAt": {
"$date": "2021-10-21T12:30:33.215Z"
},
"_id": {
"$oid": "61715d7990905adefcf314d1"
}
}]
}
and I have got newscategory collection like that
[
{
"lang": "ru",
"categories": [{
"name": "sdfsdsdcsdf",
"_id": {
"$oid": "6171499e0ba3d75082823c9a"
}
}]
},
{
"lang": "en",
"categories": [{
"name": "ooo",
"_id": {
"$oid": "61712980f8ee795c6a569dcb"
}
}, {
"name": "yuy",
"_id": {
"$oid": "61712980f8ee795c6a569dcc"
}
}, {
"name": "rtyrty",
"_id": {
"$oid": "61712980f8ee795c6a569dcd"
}
}]
}
]
Expected Output:
[
{
"_id": "61715d7990905adefcf314d0",
"lang": "ru",
"news": [
{
"title": "sdf",
"content": "sdf",
"image": "asdas",
"categoryId": "6171499e0ba3d75082823c9a",
"caregory": [
{
"name": "sdfsdsdcsdf",
"_id": "6171499e0ba3d75082823c9a"
},
]
"createdAt": "2021-10-21T12:30:33.215Z",
"_id": "61715d7990905adefcf314d1"
}
],
Match is based on both "category_id" and "categories._id".
How can I achieve result like that ?
I have this situation:
This is my tree entity where each item can be a parent item or child item of one of the same entity and each of them are related to an artist.
#Entity()
#Tree("materialized-path")
export class ArtistCommissionSetupItem {
#PrimaryGeneratedColumn({type: "bigint"})
id:number
#ManyToOne(()=>Artist, artist => artist.id, {onDelete: 'CASCADE'})
#JoinColumn()
#Index()
artist:Artist
#Column()
#Index()
name:string
#Index()
#Column({nullable: true})
enabled:boolean
#TreeParent()
parent:ArtistCommissionSetupItem
#TreeChildren()
childrens:ArtistCommissionSetupItem[]
}
The thing here is that I want to get the artist with his related commission setup items and I can do that but the result of commission setup items leftJoinAndSelect method doesn't come with the items nested as tree/child tree. I want the data of commission setup items come like findTrees() method returns it.
An example of how the data come:
"commissionSetupItems": [
{
"id": "154",
"name": "Body",
"enabled": null,
"price": null,
"createdAt": "2021-09-23T21:17:05.630Z",
"updatedAt": "2021-09-23T21:17:05.630Z"
},
{
"id": "155",
"name": "icon",
"enabled": true,
"price": "120.00",
"createdAt": "2021-09-23T21:17:05.630Z",
"updatedAt": "2021-09-23T21:17:05.630Z"
},
{
"id": "156",
"name": "Headshot",
"enabled": false,
"price": "120.00",
"createdAt": "2021-09-23T21:17:05.630Z",
"updatedAt": "2021-09-23T21:17:05.630Z"
}
}
an example of how I want the data comes:
{
"commissionSetupItems": [
{
"id": 1,
"name": "Characters",
"key": "characters",
"childrens": [
{
"id": 5,
"name": "Number of characters",
"key": "number_of_characters",
"childrens": []
}
]
},
{
"id": 2,
"name": "Body",
"key": "body",
"childrens": [
{
"id": 6,
"name": "Icon",
"key": "icon",
"childrens": []
},
{
"id": 7,
"name": "Chibi",
"key": "chibi",
"childrens": []
},
{
"id": 8,
"name": "Headshot",
"key": "headshot",
"childrens": []
},
{
"id": 9,
"name": "Torso or Burst",
"key": "torso",
"childrens": []
},
{
"id": 10,
"name": "Half body",
"key": "half_body",
"childrens": []
},
{
"id": 11,
"name": "Full body",
"key": "full_body",
"childrens": []
}
]
}
}
I can't figure out how to do this.
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();
I need to filter some users according to some fixed criteria. I have a user collection and a talent collection. The talent collection holds the reference to a master category collection.
What I need is to filter these users according to the category in the talent collection and some keys from the user collection.
For example I need to search for a user whose gender is 'male' and education 'BTech' and will have talents as a programmer and tester
my user collection is like,
{
"_id": "5f1939239bd35429ac9cd78f",
"isOtpVerified": "false",
"role": "user",
"adminApproved": 1,
"status": 0,
"languages": "Malayalam, Tamil, Telugu, Kannada",
"name": "Test user",
"email": "test#email.com",
"phone": "1234567890",
"otp": "480623",
"uid": 100015,
"bio": "Short description from user",
"dob": "1951-09-07T00:00:00.000Z",
"gender": "Male",
"education": "Btech",
"bodyType": "",
"complexion": "",
"height": "",
"weight": "",
"requests": [],
"location": {
"place": "place",
"state": "state",
"country": "country"
},
"image": {
"avatar": "5f1939239bd35429ac9cd78f_avatar.jpeg",
"fullsize": "5f1939239bd35429ac9cd78f_fullsize.png",
"head_shot": "5f1939239bd35429ac9cd78f_head_shot.jpeg",
"left_profile": "5f1939239bd35429ac9cd78f_left_profile.png",
"right_profile": "5f1939239bd35429ac9cd78f_right_profile.png"
},
"__v": 42,
"createdAt": "2020-07-23T07:15:47.387Z",
"updatedAt": "2020-08-18T18:54:22.272Z",
}
Talent collection
[
{
"_id": "5f38efef179aca47a0089667",
"userId": "5f1939239bd35429ac9cd78f",
"level": "5",
"chars": {
"type": "Fresher",
},
"category": "5f19357b50bcf9158c6be572",
"media": [],
"createdAt": "2020-08-16T08:35:59.692Z",
"updatedAt": "2020-08-16T08:35:59.692Z",
"__v": 0
},
{
"_id": "5f3b7e6f7e322948ace30a2c",
"userId": "5f1939239bd35429ac9cd78f",
"level": "3",
"chars": {
"type": "Fresher",
},
"category": "5f19359250bcf9158c6be573",
"media": [
{
"adminApproved": 0,
"status": 0,
"_id": "5f3c22573065f84a48e04a14",
"file": "id=5f1939239bd35429ac9cd78f&dir=test&img=5f1939239bd35429ac9cd78f_image_undefined.jpeg",
"description": "test",
"fileType": "image",
"caption": "test file"
},
{
"adminApproved": 0,
"status": 0,
"_id": "5f3c2d7a8c7f8336b0bfced2",
"file": "id=5f1939239bd35429ac9cd78f&dir=test&img=5f1939239bd35429ac9cd78f_image_1.jpeg",
"description": "this is a demo poster for testing",
"fileType": "image",
"caption": "A Test Poster"
}
],
"createdAt": "2020-08-18T07:08:31.532Z",
"updatedAt": "2020-08-18T19:35:22.899Z",
"__v": 2
}
]
And the category in the above document is a separate one populated to this. the category collection as,
[
{
"_id": "5f19359250bcf9158c6be573",
"status": true,
"title": "Testing",
"description": "Application tester",
"code": "test",
"characteristics": [],
"createdAt": "2020-07-23T07:00:34.221Z",
"updatedAt": "2020-07-23T07:00:34.221Z",
"__v": 0
},
{
"status": true,
"_id": "5f29829a705b4e648c28bc88",
"title": "Designer",
"description": "UI UX Designer",
"code": "uiux",
"createdAt": "2020-08-04T15:45:30.125Z",
"updatedAt": "2020-08-04T15:45:30.125Z",
"__v": 0
},
{
"_id": "5f19357b50bcf9158c6be572",
"status": true,
"title": "programming",
"description": "Java programmer",
"code": "program",
"createdAt": "2020-07-23T07:00:11.137Z",
"updatedAt": "2020-07-23T07:00:11.137Z",
"__v": 0
}
]
So my filter terms will be;
{
categories: ["5f19359250bcf9158c6be573", "5f19357b50bcf9158c6be572"],
minAge: 18,
maxAge: 25,
minHeight: 5,
maxHeight: 6,
minWeight: 50,
maxWeight: 80,
complexion: "white",
gender: "male",
}
And the expected result will be a user have both the above talents and followed conditions,
{
users: { ..User details.. },
medias: { ...medias from the matching talents.. }
}
If there are two collections you need to join them either by primary key or _id with foriegn fields and you can use $lookup with $match to filter down.
Documentation
You need to use $lookup with pipeline,
$match you condition for category match
$lookup to join users collection
$match conditions for users collections fields
$match exclude documents that don't found matching users of criteria passed in conditions
db.talents.aggregate([
{
$match: {
category: { $in: ["5f19359250bcf9158c6be573", "5f19357b50bcf9158c6be572"] }
}
},
{
$lookup: {
from: "users",
as: "users",
let: { userId: "$userId" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$$userId", "$_id"] },
{ $eq: ["$gender", "Male"] },
{ $eq: ["$education", "Btech"] }
// ... add you other match criteria here
]
}
}
}
]
}
},
{ $match: { users: { $ne: [] } } }
])
Playground
i'm new to MongoDB & Mongoose
I have data like this:
{
"_id": "5787009e494495e56d327417",
"title": "Hahaha",
"parent": null,
"depth": 0
},
{
"_id": "5787009e494495e56d327416",
"title": "Hihihi",
"parent": null,
"depth": 0
},
{
"_id": "5787009e494495e56d327415",
"title": "Huhuhu",
"parent": "5787009e494495e56d327417",
"depth": 1
}
How can I convert the data into this:
{
"_id": "5787009e494495e56d327417",
"title": "Hahaha",
"children": [
"_id": "5787009e494495e56d327415",
"title": "Huhuhu",
"children": []
]
},
{
"_id": "5787009e494495e56d327416",
"title": "Hihihi",
"children": []
}
Please help me, and sorry for my bad english !
There is no other way you have to traverse the result and create new Data in memory.
//for each item in the result {
if(item.parent !=null){
insert_item_in_tree(item);
}
//}
then build a data structure function to insert the one item appropriately as per parent id.