How to findOneAndUpdate MongoDB object inside array from multiple arrays inside object - node.js

I am new to mongodD. Although i have wrote correct logic to push object inside cardsData bankCardsArray, but i am not able to make logic to edit a card.
**I have following Data in MongoDB, **
UserData = {
"_id": "63b43ab32fc8d3c100cafecc",
"name": "Praveen Lohar",
"email": "pr********#gmail.com",
"password": "$2b$12$3nwifHakrBu94BwLXAC4Nu16Kw0.xyW8vAIPTMSgY7cYttVklDIZq",
"loginIdsArray": [
{
"title": "Airtel App",
"logoIndex": 3,
"category": "Finance",
"app": "Airtel Thanks",
"username": "p******#gmail.com ",
"password": "xxxxxxx",
"isFavourite": false,
"_id":"63b440ee738a50fc333df3ca"
}
],
"cardsData": {
"bankCardsArray": [
{
"title": "SBI CC",
"logoIndex": 72,
"category": "Bank",
"cardHolder": "Prsscscs",
"cardNumber": "524xxxxxxxx20xx",
"expiry": "23/54",
"cvv": "00",
"isFavourite": false,
"_id": "63b974adb9acaa24a4ebec8b"
},
{
"title": "AXIS CC",
"logoIndex": 85,
"category": "Bank",
"cardHolder": "blsllslss",
"cardNumber": "524xxxxxxxx20xx",
"expiry": "23/54",
"cvv": "00",
"isFavourite": false,
"_id": "63b974adb9acaa24a4ebe5f"
}
],
"identityCardsArray": [
{
"title": "Aadhar Card",
"logoIndex": 98,
"category": "Identity",
"cardHolder": "Name_1",
"cardNumber": "54*******455454",
"issueDate": "2012",
"dob": "23/05",
"isFavourite": false,
"_id":"63b974e6bd0d03c116955f67"
}
],
"licenseCardsArray": [
{
"title": "Two Wheeler License",
"logoIndex": 0,
"category": "License",
"cardHolder": "Klaus Michealson",
"licenseNumber": "RJ/22/ADL-542/474/01",
"expiry": "2036",
"dob": "13/06",
"isFavourite": false,
"_id":"63b97535bd0d03c116955f69"
}
]
}
}
I want to find the user with _id
Then for that user i want to got to cardsData object
Then in cardsData object i want to got to bankCardsArray
Then in bankCardsArray , i want to update fields of a card with particular id
Const res = findOneAndUpdate(
{ 'cardsData.bankCardsArray._id':card_id },
{ $set{ 'cardsData.bankCardsArray.$.title': req.body.title });

Use "." operator to access nested fields.
Refer these mongodb documentation
query-array-of-documents
query-embedded-documents.
Hope this helps.

Related

Retrieve object information within an array with mongoose

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();

How to query nested object in mongodb

I'm new to mongodb and I've been trying to query this doc for awhile now.
Im trying to query all the rooms that have a room name of 100.
json
{
"count": 3,
"reviews": [
{
"_id": "5f9d42a0a8e71e004643f584",
"user": {
"_id": "5f7308cde0a4a7a66bc3d184",
"name": "Guest"
},
"room": {
"_id": "5f98f9321fd5bb0045b3d886",
"name": "100",
},
"rating": 4,
},
{
"_id": "5f9d431ea8e71e004643f585",
"user": {
"_id": "5f7308cde0a4a7a66bc3d184",
"name": "Guest",
},
"room": {
"_id": "5f98f9321fd5bb0045b3d886",
"name": "100",
},
"rating": 5,
},
{
"_id": "5f9e74fea6c06a0046d3cae2",
"user": {
"_id": "5f7308cde0a4a7a66bc3d184",
"name": "Guest",
},
"room": {
"_id": "5f98fa8b1fd5bb0045b3d88a",
"name": "300",
},
"rating": 5,
}
]}
what I've tried
1. find({},{"reviews.room.name": {$eq: "100"}}) // getting a projection error
2. find({"reviews.room.name": "100"}) // getting null
Any help to the right direction would be greatly appreciated.
Check out the docs about how to use find:
https://docs.mongodb.com/manual/reference/method/db.collection.find/
and try this
db.reviews.find({
"room.name": "100"
})
Here is the playground with your example: https://mongoplayground.net/p/dPfH5fSOePq
did u try this ? const response = await Room.find({name: "100"})

Flter mongodb database using mongoose nodejs

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

MongoDB create product summary collection

Say I have a product collection like this:
{
"_id": "5a74784a8145fa1368905373",
"name": "This is my first product",
"description": "This is the description of my first product",
"category": "34/73/80",
"condition": "New",
"images": [
{
"length": 1000,
"width": 1000,
"src": "products/images/firstproduct_image1.jpg"
},
...
],
"attributes": [
{
"name": "Material",
"value": "Synthetic"
},
...
],
"variation": {
"attributes": [
{
"name": "Color",
"values": ["Black", "White"]
},
{
"name": "Size",
"values": ["S", "M", "L"]
}
]
}
}
and a variation collection like this:
{
"_id": "5a748766f5eef50e10bc98a8",
"name": "color:black,size:s",
"productID": "5a74784a8145fa1368905373",
"condition": "New",
"price": 1000,
"sale": null,
"image": [
{
"length": 1000,
"width": 1000,
"src": "products/images/firstvariation_image1.jpg"
}
],
"attributes": [
{
"name": "Color",
"value": "Black"
},
{
"name": "Size",
"value": "S"
}
]
}
I want to keep the documents separate and for the purpose of easy browsing, searching and faceted search implementation, I want to fetch all the data in a single query but I don't want to do join in my application code.
I know it's achievable using a third collection called summary that might look like this:
{
"_id": "5a74875fa1368905373",
"name": "This is my first product",
"category": "34/73/80",
"condition": "New",
"price": 1000,
"sale": null,
"description": "This is the description of my first product",
"images": [
{
"length": 1000,
"width": 1000,
"src": "products/images/firstproduct_image1.jpg"
},
...
],
"attributes": [
{
"name": "Material",
"value": "Synthetic"
},
...
],
"variations": [
{
"condition": "New",
"price": 1000,
"sale": null,
"image": [
{
"length": 1000,
"width": 1000,
"src": "products/images/firstvariation_image.jpg"
}
],
"attributes": [
"color=black",
"size=s"
]
},
...
]
}
problem is, I don't know how to keep the summary collection in sync with the product and variation collection. I know it can be done using mongo-connector but i'm not sure how to implement it.
please help me, I'm still a beginner programmer.
you don't actually need to maintain a summary collection, its redundant to store product and variation summary in another collection
instead of you can use an aggregate pipeline $lookup to outer join product and variation using productID
aggregate pipeline
db.products.aggregate(
[
{
$lookup : {
from : "variation",
localField : "_id",
foreignField : "productID",
as : "variations"
}
}
]
).pretty()

Query to retrieve every subdocument alone without passing parent id using Mongoose

Here i like to explain my problem.
How can i write a mongoose query to retrieve every subdocument from JSON without passing parent_id.
[
{
"_id": "56a320003fe17cc7363dd0d7",
"name": "Leanna Jacobson",
"gender": "female",
"friends": [
{
"id": 0,
"name": "Riley Case"
},
{
"id": 1,
"name": "Herman Carter"
},
{
"id": 2,
"name": "Pacheco Woodard"
}
]
},
{
"_id": "56a3200001501cfa1ea2641d",
"name": "Juliana Bonner",
"gender": "female",
"friends": [
{
"id": 0,
"name": "Keller Woodward"
},
{
"id": 1,
"name": "Fern Knight"
},
{
"id": 2,
"name": "Cain Richards"
}
]
},
{
"_id": "56a3200006864c78ecb1aeed",
"name": "Gena Stark",
"gender": "female",
"friends": [
{
"id": 0,
"name": "Kate Franco"
},
{
"id": 1,
"name": "Araceli Mcclure"
},
{
"id": 2,
"name": "Molly Nelson"
}
]
},
{
"_id": "56a320006d868155161038b6",
"name": "Eve Gonzalez",
"gender": "female",
"friends": [
{
"id": 0,
"name": "Pam Lang"
},
{
"id": 1,
"name": "Christy Marks"
},
{
"id": 2,
"name": "Donovan Warren"
}
]
},
{
"_id": "56a3200066b94852f5680568",
"name": "Coleman Wooten",
"gender": "male",
"friends": [
{
"id": 0,
"name": "Roberta Olson"
},
{
"id": 1,
"name": "Roseann Reid"
},
{
"id": 2,
"name": "Kerri Russell"
}
]
}
]
Here i need to retrieve every friends details from the subdocument array friends for every parent.
so how can i write query for this?????
Suppose the name of your schema is Person, try this one.
//find all document, only select `friends` field from every document
Person.find({}, 'friends', function (err, friends) {
// the return friends is the [[friends], [friends], ...]
});

Resources