Retrieve value from mongoose object after query - node.js

I have a query as follows :
await Categories.findOne({slug : _gender} , { _id : 0 , categories :{$elemMatch : {slug : _mainCategory}}})
and the model is this :
const categoriesSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String },
slug: { type: String }, ==> match first param with this
categories: [
{
_id: mongoose.Schema.Types.ObjectId,
title: { type: String },
slug: { type: String }, ==> match the second param with this
categories: [ ==> retrieve this field
{
_id: mongoose.Schema.Types.ObjectId,
title: { type: String },
slug: { type: String },
},
],
},
],
});
_gender and _mainCategory are params.
The output it gives is as follows:
{
"categories": [
{
"id": "12",
"title": "Ayakkabı",
"slug": "kadin-ayakkabi", // ==> this is the { _id : 0 , categories :{$elemMatch : {slug : _mainCategory}} part, one level above this is the part which matches the {slug : _gender}
"image": "https://webizade.com/bm/img/",
"categories": [ // ===> this is the value I want to retrieve after the query
{
"id": "100",
"title": "Topuklu Ayakkabı",
"filter_title": "ayakkabi",
"slug": "kadin-topuklu-ayakkabi-x-g1-c107",
"image": "https://webizade.com/bm/img/"
},
{
"id": "101",
"title": "Spor Ayakkabı",
"filter_title": "ayakkabi",
"slug": "spor-ayakkabi",
"image": "https://webizade.com/bm/img/"
},
{
"id": "102",
"title": "Günlük Ayakkabı",
"filter_title": "ayakkabi",
"slug": "kadin-gunluk-ayakkabi-x-g1-c1352",
"image": "https://webizade.com/bm/img/"
},
{
"id": "103",
"title": "Babet",
"filter_title": "ayakkabi",
"slug": "kadin-babet-x-g1-c113",
"image": "https://webizade.com/bm/img/"
},
{
"id": "104",
"title": "Sandalet",
"filter_title": "ayakkabi",
"slug": "kadin-sandalet-x-g1-c111",
"image": "https://webizade.com/bm/img/"
},
{
"id": "105",
"title": "Terlik",
"filter_title": "ayakkabi",
"slug": "kadin-terlik-x-g1-c110",
"image": "https://webizade.com/bm/img/"
},
{
"id": "144",
"title": "Kar Botu",
"filter_title": "ayakkabi",
"slug": "kar-botu",
"image": "https://webizade.com/bm/img/"
}
]
}
]
}
As far as matching the correct object goes, this is correct. However, I want to retrieve the "categories" array inside the outer categories array after finding the correct object. But I don't know the correct syntax for doing that.
Appreciate any help.

Related

Joining only matching elements

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 ?

how to update embed document in mongoDB with mongoose

i have course model like
const courseSchema = new mongoose.Schema({
name:{
type: String,
required:[true,'course must have a name.'],
unique:true
},
duration :Number,
description :String,
imageCover :String,
images:Array,
price :Number,
curriculum:
[
{
week:Number,
description:String,
total:Number,
completed:Number,
progress:Number,
links:
[
{
name:String,
link:String,
img:String,
watched:{
type:Boolean,
default:false
}
}
]
}
],
tutors:[
{
type: mongoose.Schema.ObjectId,
ref:'user'
}
]
},
{
toJSON:{virtuals : true},
toObject:{virtuals : true}
});
i want to add new objects to links array in curriculum .client side will patch request with week object id , name and link ,inside update handler i am doing somthing like this.
const cour = await Course.findOneAndUpdate({"caricullum._id":req.params.w},
{$push:{name:req.body.name,link:req.body.link}},{
new : true,
});
w params contain curriculum week _id
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3e2"
},
"images": [],
"tutors": [],
"name": "c/c++",
"duration": 8,
"price": 1299,
"imageCover": "cool_lion.jpg",
"description": "",
"curriculum": [
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3e3"
},
"week": 1,
"description": "introduction to microcontroller and microprocesor",
"links": [
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e4"
},
"name": "introduction",
"link": "https://www.youtube.com/embed/d0e6ScoS3Sw"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e5"
},
"name": "difference between mc and mp",
"link": "https://www.youtube.com/embed/dcNk0urQsQM"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e6"
},
"name": "building with microcontroller vs boards(arduino uno)",
"link": "https://www.youtube.com/embed/IdEcm3GU7TM"
}
]
},
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3e7"
},
"week": 2,
"description": "introduction to arduino uno",
"links": [
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e8"
},
"name": "introduction to arduino uno",
"link": "https://www.youtube.com/embed/BiCSW6QR6HA"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e9"
},
"name": "IO PINS",
"link": "https://www.youtube.com/embed/OZGMLOwHYf8"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ea"
},
"name": "setting up arduno uno for programming",
"link": "https://www.youtube.com/embed/ELUF8m24sZo"
}
]
},
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3eb"
},
"week": 3,
"description": "interfacing with different sensors",
"links": [
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ec"
},
"name": "LED Blinking(OUTPUT)",
"link": "https://www.youtube.com/embed/dnPPoetX0uw"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ed"
},
"name": "interfacing with button(INPUT)",
"link": "https://www.youtube.com/embed/58Ynhqmvzoc"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ee"
},
"name": "16x2 LCD",
"link": "https://www.youtube.com/embed/Mr9FQKcrGpA"
}
]
}
],
"__v": 0
}
how to query for correct week document with req.params.w and push new document into links array
use arrayFilters
db.collection.update({},
{
$push: {
"curriculum.$[elem].links": {
link: "a",
name: "b",
whatched: "c"
}
}
},
{ new:true,
arrayFilters: [
{
"elem.week": 1
}
]
})
https://mongoplayground.net/p/nLV9UzbJlsc

How to insert a list and insert a nested embed list in MongoDB

I have this structure :
{
"_id": "blablabla",
"UUID": "50ED0565C5BF",
"Email": "foobar#bar.ca",
"FirstName": "Bacel",
"LastName": "ELbs",
"ClientID": "sa-sa",
"UserSettings": {
"dateRangeMode": "1",
"skillsMode": "1",
"CalendarViewMode": "One Month"
},
"Filters": [{
"Type": "Calendar",
"Filter": [],
"DefaultFilterID": ""
}, {
"Type": "Calendar",
"desc": "test",
"Filter": [],
"isDefault": false
}]
}
My objective is to first insert one new object to the Filters array and insert multiple items to the Filters.Filter embedded array :
so I'm trying the following approch :
static async saveFilter(UUID, Type, desc, isDefault, aFilters) {
//let objectID = UUID.replace(/-/g, "");
return await user.update({
UUID: UUID
}, {
$push: {
Filters: {
Type: Type,
desc: desc,
isDefault: isDefault
},
"Filters.Filter": ["a","b","c"]
}
});
}
I keep having this error :
Cannot create field 'Filter:' in element {Filters: [ { Type:
"Calendar", Filter: [], DefaultFilterID: "" }, { Type: "Calendar",
desc: "test", isDefault: false } ]}
But I don't want to creat a new field, I simply want to add elements,
desired output is something like :
{
"_id": "blablabla",
"UUID": "50ED0565C5BF",
"Email": "foobar#bar.ca",
"FirstName": "Bacel",
"LastName": "ELbs",
"ClientID": "sa-sa",
"UserSettings": {
"dateRangeMode": "1",
"skillsMode": "1",
"CalendarViewMode": "One Month"
},
"Filters": [{
"Type": "Calendar",
"Filter": [],
"DefaultFilterID": ""
}, {
"Type": "Calendar",
"desc": "test",
"Filter": [],
"isDefault": false
},
{
"Type": "Tower",
"desc": "Tesla",
"Filter": ["a","b","c"],
"isDefault": false
}]
Is this what you're looking for?
(playground)
db.users.update({
UUID: UUID
},
{
$push: {
Filters: {
Type: Type,
desc: desc,
isDefault: isDefault,
"Filter": [
"a",
"b",
"c"
]
}
}
})

Create Mongoose Find and populate from multiple tables with property set

I'll be grateful for help with Mongoose. I have 3 tables: (Users)Table of users, (Animals)table of animals and table AnimalComments. So (AnimalComments)table reference users and animals.
const schemaComment = new mongoose.Schema({
userRef: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
animalRef: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Animal'
},
content: {
type: String
}
});
const schemaAnimal = new mongoose.Schema({
name: {
type: String
},
isCommentedByMe: {
type : Boolean,
default: false
},
commentCount: {
type : Number,
default: 0
}
});
What I want: I have animals. Users can add comment to animal. When user comment animal his comment is added to table AnimalComments where is stored userRef (userId), animalRef (animalId) and user comment text. Then in request response I want return all animals from table Animals but I need update property commentCount and isCommentedByMe based on value from table AnimalComments.
Response from table Animals:
{
"animals": [
{
"isCommentedByMe": false,
"commentCount": 0,
"name": "Jessica",
"userRef": {
"id": "5dc9bdf3dd5cae00177e184d"
},
"id": "5dcedd48368e9800176f2ef3"
}
]
}
Response from table Users:
{
"users": [
{
"name": "Jony Cash",
"id": "5dc9bdf3dd5cae00177e184d"
}
]
}
Response from table AnimalComments:
{
"comments": [
{
"userRef": "5dc9bdf3dd5cae00177e184d",
"animalRef": "5dcedd48368e9800176f2ef3",
"content": "Sample text"
}
]
}
I want result for exmaple:
{
"animals": [
{
"isCommentedByMe": true,
"commentCount": 4,
"name": "Jessica",
"userRef": {
"id": "5dc9bdf3dd5cae00177e184d"
},
"id": "5dcedd48368e9800176f2ef3"
}
]
}
You don't need to keep isCommentedByMe and commentCount fields in animal schema.
And you need to be able access comments from your animals. But in animal schema there is no field to make that connection. So we need to use virtual population.
So your animal schema must be like this:
const schemaAnimal = new mongoose.Schema(
{
name: {
type: String
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
// Virtual populate
schemaAnimal.virtual("comments", {
ref: "Comment", //must be changed to the name you used for Comment model.
foreignField: "animalRef",
localField: "_id"
});
Now, we can use the following code to populate the comments.
router.get("/animals", async (req, res) => {
const animals = await Animal.find({}).populate("comments");
res.send(animals);
});
This will give you a result like this:
[
{
"_id": "5dd66c73069f88614c12b394",
"name": "Animal 1",
"__v": 0,
"comments": [
{
"_id": "5dd66cfd069f88614c12b39a",
"userRef": "5dd66b54c5195127ec5a1b82",
"animalRef": "5dd66c73069f88614c12b394",
"content": "User 1 - Animal 1",
"__v": 0
},
{
"_id": "5dd66d30069f88614c12b39d",
"userRef": "5dd66b71c5195127ec5a1b83",
"animalRef": "5dd66c73069f88614c12b394",
"content": "User 2 - Animal 1",
"__v": 0
}
],
"id": "5dd66c73069f88614c12b394"
},
{
"_id": "5dd66c7d069f88614c12b395",
"name": "Animal 2",
"__v": 0,
"comments": [
{
"_id": "5dd66d09069f88614c12b39b",
"userRef": "5dd66b54c5195127ec5a1b82",
"animalRef": "5dd66c7d069f88614c12b395",
"content": "User 1 - Animal 2",
"__v": 0
}
],
"id": "5dd66c7d069f88614c12b395"
},
{
"_id": "5dd66c88069f88614c12b396",
"name": "Animal 3",
"__v": 0,
"comments": [
{
"_id": "5dd66d46069f88614c12b39e",
"userRef": "5dd66b71c5195127ec5a1b83",
"animalRef": "5dd66c88069f88614c12b396",
"content": "User 2 - Animal 3",
"__v": 0
}
],
"id": "5dd66c88069f88614c12b396"
}
]
To convert this result to what you wanted, we can use map like this:
Please note that, you need to set loggedInUserId variable to logged in user's id.
router.get("/animals", async (req, res) => {
const loggedInUserId = "5dd66b54c5195127ec5a1b82";
const animals = await Animal.find({}).populate("comments");
const result = animals.map(animal => {
return {
id: animal._id,
name: animal.name,
isCommentedByMe:
animal.comments.filter(c => c.userRef.toString() === loggedInUserId)
.length > 0,
commentCount: animal.comments.length
};
});
res.send(result);
});
The result will be like this:
[
{
"id": "5dd66c73069f88614c12b394",
"name": "Animal 1",
"isCommentedByMe": true,
"commentCount": 2
},
{
"id": "5dd66c7d069f88614c12b395",
"name": "Animal 2",
"isCommentedByMe": true,
"commentCount": 1
},
{
"id": "5dd66c88069f88614c12b396",
"name": "Animal 3",
"isCommentedByMe": false,
"commentCount": 1
}
]
And the answer for the question in the comments is: (how to reference User)
const animals = await Animal.find({}).populate({
path: "comments",
model: Comment,
populate: [
{
path: "userRef",
model: User
}
]
});
This will give you the userRef like this:
[
{
"_id": "5dd66c73069f88614c12b394",
"name": "Animal 1",
"__v": 0,
"comments": [
{
"_id": "5dd66cfd069f88614c12b39a",
"userRef": {
"_id": "5dd66b54c5195127ec5a1b82",
"name": "User 1",
"__v": 0
},
"animalRef": "5dd66c73069f88614c12b394",
"content": "User 1 - Animal 1",
"__v": 0
},
{
"_id": "5dd66d30069f88614c12b39d",
"userRef": {
"_id": "5dd66b71c5195127ec5a1b83",
"name": "User 2",
"__v": 0
},
"animalRef": "5dd66c73069f88614c12b394",
"content": "User 2 - Animal 1",
"__v": 0
}
],
"id": "5dd66c73069f88614c12b394"
},
{
"_id": "5dd66c7d069f88614c12b395",
"name": "Animal 2",
"__v": 0,
"comments": [
{
"_id": "5dd66d09069f88614c12b39b",
"userRef": {
"_id": "5dd66b54c5195127ec5a1b82",
"name": "User 1",
"__v": 0
},
"animalRef": "5dd66c7d069f88614c12b395",
"content": "User 1 - Animal 2",
"__v": 0
}
],
"id": "5dd66c7d069f88614c12b395"
},
{
"_id": "5dd66c88069f88614c12b396",
"name": "Animal 3",
"__v": 0,
"comments": [
{
"_id": "5dd66d46069f88614c12b39e",
"userRef": {
"_id": "5dd66b71c5195127ec5a1b83",
"name": "User 2",
"__v": 0
},
"animalRef": "5dd66c88069f88614c12b396",
"content": "User 2 - Animal 3",
"__v": 0
}
],
"id": "5dd66c88069f88614c12b396"
}
]

Get parent to child relation with mongodb aggregation

I have one collection called "location". in this collection all child and parent collection are stores. now I want to create a query who returns me parent to child comma separated string.
Collection
businessId: { type: mongoose.Schema.Types.ObjectId, ref: 'admin' },
parentId: { type: mongoose.Schema.Types.ObjectId, ref: 'location' },
name: { type: String },
image: { type: String },
imageManipulation: { type: String },
locationColor: [{ range: { type: String }, color: { type: String } }],
area: {},
settings: {},
status: { type: String, enum: [0, 1], default: 1 },
isChild: { type: String, enum: [0, 1] },
parentPosition: { type: String }
In the above collection, you can see parentId field. if the location is a child then it have parentId. if the location is a parent then parentId will null. parent location can N level child location.
Collection Data
[{
"_id": ObjectId("5ce4f84547e90a0b9c3c4763"),
"name": "Test",
"settings": {
"zoom": "3",
"positionX": "69",
"positionY": "69",
"width": "500",
"height": "334"
},
"parentId": null,
"image": "1558509637101.jpg",
"status": "0",
"businessId": ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor": [],
"updatedAt": ISODate("2019-05-22T12:59:26.013Z"),
"createdAt": ISODate("2019-05-22T07:20:37.112Z"),
"__v": 0
},
{
"_id": ObjectId("5ce50caf09359e1b8ccf5c79"),
"name": "Test sub 1",
"settings": {
"zoom": "3",
"positionX": "48",
"positionY": "3",
"width": "500",
"height": "334"
},
"area": "",
"parentId": ObjectId("5ce4f84547e90a0b9c3c4763"),
"image": "1558514863396.jpg",
"status": "0",
"businessId": ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor": [],
"updatedAt": ISODate("2019-05-22T12:59:21.883Z"),
"createdAt": ISODate("2019-05-22T08:47:43.421Z"),
"__v": 0
},
{
"_id": ObjectId("5ce53977e46da33e6cfdd9d1"),
"name": "Test Sub 2",
"settings": {
"zoom": "5",
"positionX": "0",
"positionY": "0",
"width": "500",
"height": "334"
},
"area": "",
"parentId": ObjectId("5ce50caf09359e1b8ccf5c79"),
"image": "1558526327126.jpg",
"businessId": ObjectId("5cbd61dc3b56b902284ea388"),
"locationColor": [],
"updatedAt": ISODate("2019-05-22T11:58:47.147Z"),
"createdAt": ISODate("2019-05-22T11:58:47.147Z"),
"__v": 0
}]
Expected Result
Test, Test sub 1, Test Sub 2
Expected result in JSON
[{
"_id": ObjectId("5ce4f84547e90a0b9c3c4763"),
"name": "Test",
},
{
"_id": ObjectId("5ce50caf09359e1b8ccf5c79"),
"name": "Test, Test sub 1",
},
{
"_id": ObjectId("5ce53977e46da33e6cfdd9d1"),
"name": "Test, Test sub 1, Test Sub 2",
}]
You basically need $graphLookup for recursive loop over the same collection.
db.location.aggregate([
{ "$graphLookup": {
"from": "location",
"startWith": "$parentId",
"connectFromField": "parentId",
"connectToField": "_id",
"as": "parent"
}},
{ "$project": {
"name": {
"$concat": [
"$name",
{ "$reduce": {
"input": "$parent",
"initialValue": "",
"in": { "$concat": [",", "$$this.name", "$$value"] }
}}
]
}
}}
])
Which will output
[
{
"_id": ObjectId("5ce4f84547e90a0b9c3c4763"),
"name": "Test"
},
{
"_id": ObjectId("5ce50caf09359e1b8ccf5c79"),
"name": "Test sub 1,Test"
},
{
"_id": ObjectId("5ce53977e46da33e6cfdd9d1"),
"name": "Test Sub 2,Test sub 1,Test"
}
]
MongoPlayground

Resources