Possible to only query a sub document in Mongoose? - javascript

This is my test collection
[
{
"_id": "637cbf94b4741277c3b53c6c",
"text": "outter",
"username": "test1",
"address": [
{
"text": "inner",
"username": "test2",
"_id": "637cbf94b4741277c3b53c6e"
}
],
"__v": 0
}
]
If I do
t1 = await doc.find({}, 'text').exec();
console.log(JSON.stringify(t1, null, 2));
I get
[
{
"_id": "637cbf94b4741277c3b53c6c",
"text": "outter"
}
]
So here it finds the parent text.
Question
How do I get Mongoose to query the sub document instead of the parent?

You can project the sub document(s) like this:
t1 = await doc.find({}, {'address.text':1}).exec();
See how it works on the playground example

If you only want the sub document, not even the _id of the parent:
await doc.find(
{},
{
_id: 0,
'address.text': 1
}
).exec();`

Related

TypeORM Select Column from relation without using QueryBuilder

If anyway to select columns from relation without using querybuilder ???
This is my current query:
const areas = await this.areaRepository.find({
where: { ...isActive },
relations: ["division"],
});
Output :
{
"id": 1,
"version": 9,
"isActive": 1,
"createdBy": null,
"updatedBy": 1,
"createAt": "2022-04-18T15:42:12.000Z",
"updatedAt": "2022-09-23T11:04:53.000Z",
"name": "Dhaka",
"division": {
"id": 3,
"version": 1,
"isActive": 1,
"createdBy": null,
"updatedBy": null,
"createAt": "2022-04-18T15:42:00.000Z",
"updatedAt": "2022-04-18T15:42:00.000Z",
"name": "Dhaka"
}
},
But is there anything like:
const areas = await this.areaRepository.find({
select: ['id','division.id division_id']
where: { ...isActive },
relations: ["division"],
});
And the output will be:
{
"id": 1,
"division_id": 3
}
This is a duplicated question of: How to select fields from joined table using TypeORM repository?
You can check the answer here. Also this depends on which TypeOrm version you are currently using, as far as I know on version under 0.3 this doesn't work.

Update a field in nested array of objects containing another array of objects in mogoDb (JavaScript)

I have the following structure of Student collection in MongoDb:
{
"_id": "st1",
"student_courses": [
{
"_id": "c1",
"course_name": "Node",
"image": [
{
"_id": "c1img1",
"image": "img1.jpeg"
}
]
},{
"_id": "c2",
"course_name": "React",
"image": [
{
"_id": "c2img2",
"image": "img2.jpeg"
}
]
}
],
}
Now, I want to update the image name of img1.jpeg in all the documents that have same image name. So what I am doing is this:
Student.updateMany(
{ "student_courses._id": "c1"},
{
$set: {
"student_courses.$.course_name": "Node Crash Course",
"student_courses.$.image[0].image": complete_image_name,
},
}
);
Unexpectedly, this is updating course_name field but image. I have tried using $ positional argument instead of [0] but got the error Too many positional arguments ...... I don't know how to do that. My expected output should look like this:
{
"_id": "st1",
"student_courses": [
{
"_id": "c1",
"course_name": "Node Crash Course",
"image": [
{
"_id": "c1img1",
"image": "complete_image_name.jpeg"
}
]
},
:::::::::::::::::::
:::::::::::::::::::
],
}
{
"_id": "st2",
"student_courses": [
{
"_id": "c1",
"course_name": "Node Crash Course",
"image": [
{
"_id": "c1img1",
"image": "complete_image_name.jpeg"
}
]
},
:::::::::::::::::::
:::::::::::::::::::
],
}
Moreover, I have implemented almost every method posted in similar questions. Thanks in advance for any help.
Try to change the way you are referring to the first element in the array:
Student.updateMany(
{ "student_courses._id": "c1"},
{
$set: {
"student_courses.$.course_name": "Node Crash Course",
"student_courses.$.image.0.image": complete_image_name,
},
}
);

How can i get an index of an Array in an Array of a Json Doc

I have a Json Doc which i get from my back end which looks like the one below. It has an emails Array which the doc under it has and email array. I need to get the index the email array is part of which has a match for an email address so i can update the doc. i used lodash before to search for a key in a array of docs before with _.find and _.indexOf but not sure how this would work in an Array of Array case.
{
"_type": "email_campaign",
"status": "Active",
"start_date": "04/17/2020",
"template_id": "template::0a2decdd-3acd-4661-9721-1a9ec0d039e6",
"summary": "Update",
"metrics": {
"first_email_sent": "",
"last_email_send": "2020-04-17T22:11:52.317Z",
"nbr_of_emails": 185,
"nbr_of_bounces": 1,
},
"history": {
"created_on": "04/17/2020 13:24:33",
},
"emails": [
{
"email": [
"DCustomer#gmail.com"
],
"track_request": "track_request::da07bd4b-b03e-4ecc-9d90-32e85cdb5b3a",
"tracking_nbr": "MD1dpjR6d"
},
{
"email": [
"ACustomer#matcocomponents.com",
"BCustomer#matcocomponents.com",
],
"track_request": "track_request::6f64cee1-d38e-4d68-94a2-c3c7d1287984",
"tracking_nbr": "YM1sMRX3nl"
},
{
"email": [
"ACustomer#gmail.com"
],
"track_request": "track_request::92606d4f-f9e6-457f-9156-167eb068f05b",
"tracking_nbr": "gj6dwIyHdE"
},
],
"_id": "3ed76589-4063-49f6-a21e-9ca16981d102"
}
You could use findIndex and includes:
const index = docs.emails.findIndex(item => item.email.includes('ACustomer#matcocomponents.com'))
try this:
emailToFind="xxxxxxxxx"
var indexes=[]
var test= res.emails.map((el1,i1)=>{
el.email.map((el2,i2)=>{
if (el2===emailToFind){
indexes.push(i1)
}
})
})

How can I merge two mongo collections?

I am banging my head against the wall on this...
SEE UPDATE 1 (below) !
I am merging two collections together... I looked at this example ( and ~several~ other examples here on SO ... )
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#lookup-single-equality
I think I am really close, but my expected results are not the same as what I would expect out of the example.
Here is the schema for 'Event'
const EventSchema = new Schema({
name: {type: String, required: true},
})
Here is some 'Event' data
[
{
"_id": "5e8e4fcf781d96df5c1f5358",
"name": "358 Event"
},
{
"_id": "5e8e55c5a0f5fc1431453b5f",
"name": "b5f Event"
}
]
Here is 'MyEvent' schema:
const MyEventSchema = new Schema({
userId: {type: Schema.Types.ObjectId, required: true},
eventId: {type: Schema.Types.ObjectId, required: true},
})
Here is some 'MyEvent' data
[
{
"_id": "5e8f4ed2ddab5e3d04ff30b3",
"userId": "5e6c2dddad72870c84f8476b",
"eventId": "5e8e4fcf781d96df5c1f5358",
}
]
Here is my code ( the code is wrapped in a promise so it returns resolve and reject with data )
var agg = [
{
$lookup:
{
from: "MyEvent",
localField: "_id",
foreignField: "eventId",
as: "userIds"
}
}
];
Event.aggregate(agg)
.then( events => {
return resolve(events);
})
.catch(err => {
return reject(null);
})
Here are my results,
[
{
"_id": "5e8e4fcf781d96df5c1f5358",
"name": "358 Event",
"__v": 0,
"UserIds": []
},
{
"_id": "5e8e55c5a0f5fc1431453b5f",
"name": "b5f Event",
"__v": 0,
"UserIds": []
}
]
I expect to see UserIds filled in for event '358 Event', like this
What am I missing ???
[
{
"_id": "5e8e4fcf781d96df5c1f5358",
"name": "358 Event",
"__v": 0,
"UserIds": [
{"userId": "5e6c2dddad72870c84f8476b"}
]
},
{
"_id": "5e8e55c5a0f5fc1431453b5f",
"name": "b5f Event",
"__v": 0,
"UserIds": []
}
]
UPDATE 1
I found a mongo playground and what I have works there, but it doesn't work in my code ??
https://mongoplayground.net/p/fy-GP_yx5j7
In case the link breaks, here is configuration: * select 'bson multiple collections'
db={
"collection": [
{
"_id": "5e8e4fcf781d96df5c1f5358",
"name": "358 Event"
},
{
"_id": "5e8e55c5a0f5fc1431453b5f",
"name": "b5f Event"
}
],
"other": [
{
"_id": "5e8f4ed2ddab5e3d04ff30b3",
"userId": "5e6c2dddad72870c84f8476b",
"eventId": "5e8e4fcf781d96df5c1f5358",
}
]
}
Here is Query:
db.collection.aggregate([
{
$lookup: {
from: "other",
localField: "_id",
foreignField: "eventId",
as: "userIds"
}
}
])
Here is the result:
[
{
"_id": "5e8e4fcf781d96df5c1f5358",
"name": "358 Event",
"userIds": [
{
"_id": "5e8f4ed2ddab5e3d04ff30b3",
"eventId": "5e8e4fcf781d96df5c1f5358",
"userId": "5e6c2dddad72870c84f8476b"
}
]
},
{
"_id": "5e8e55c5a0f5fc1431453b5f",
"name": "b5f Event",
"userIds": []
}
]
any suggestions as to why this doesn't work in my code... but works in the playground?
UPDATE 2
I found this:
Need a workaround for lookup of a string to objectID foreignField
UPDATE 3
I have changed the schema to use ObjectId for ids now
still doesn't work
And they are ObjectIds :
RESOLUTION:
So the real answer was a combination of Update 2 and Update 3 and using the right collection name in the lookup.
Update 2 is pretty much my very same question... just using different table names
Update 3 is the correct way to solve this issue.
Mohammed Yousry pointed out the collection name might be wrong... so I looked at my schema and I did have it wrong - changed the name to the right name (along with ObjectId types) and it worked !
It seems there's a typo in from property in $lookup, MyEvent maybe not the collection name
db.collection.aggregate([
{
$lookup: {
from: "MyEvent", // here is the issue I think, check the collection name and make sure that it matches the one you write here
localField: "_id",
foreignField: "eventId",
as: "userIds"
}
}
])
in mongo playground you attached in the question, if you change the 'other' in the $lookup to anything else, or make a typo in it .. like others instead of other, you will face the same issue
so check that there is no typo in the word MyEvent that you populate from

How to delete a paticular Object in an array inRethinkDB

I am Just trying to learn RethinkDB.I am little Bit Confused That how to delete an single Object in an array,What is the Exact query I have to use if i have to delete this Object
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
}
from whoLikedIt Array
My data
{
"comments": [ ],
"id": "c242c74d-03d9-4963-9a22-4779facb8192" ,
.....
"views": 0 ,
"whoLikedIt": [
{
"name": "Vignesh Warar" ,
"username": "d97bf210-c42d-11e6-b783-07b5fe048705"
},
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
},
]
.....
}
My Try
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(
{whoLikedIt:r.row('whoLikedIt').filter({username:"B97bf210-c4d2d-11e6-b783-07b5fev048705"}).delete()}
)
Throws Me a error
e: Cannot nest writes or meta ops in stream operations. Use FOR_EACH instead in:
You want:
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(function(row) {
return {whoLikedIt: row('whoLikedIt').filter(function(obj) {
return obj('username').ne("B97bf210-c4d2d-11e6-b783-07b5fev048705");
})};
})

Categories