find element in array within array mongoose - javascript

I have this data:
[
{
contacts: [ [Object] ],
_id: 614a1301a926d73628d791fe,
username: 'erick',
socketId: 'OB8uqmHnsGPKC3gcAAAB'
},
{
contacts: [
contacts: [ [Object] ],
_id: 614a1301a926d73628d791fe,
username: 'erick',
socketId: 'OB8uqmHnsGPKC3gcAAAB'
],
_id: 614a1306a926d73628d79204,
username: 'tachancka',
socketId: 'cN333_zn8r48K_0tAAAB'
}
]
And i need to find the username of 'erick' inside 'tachancka' contacts.
I have tried a few ways to do it but none of them worked for me, returning null.
For example:
User.findOne({contacts: {$elemMatch:{'username': 'erick'}}})
Or:
User.findOne({'contacts.username': 'erick'})

pls refer to sample here: https://mongoplayground.net/p/Np_MdrubPgT
you may use
db.User.find({
username: "tachancka",
"contacts.username": "erick"
})
When you have array of objects and if you want to match all the field within object then we use $elemMatch, here in your case i feel username is not part of contacts array hence you will not use $elemMatch

Related

Get an array of items from an object- typescript

I have an object with the below structure:
Order: [
{
id: '001',
type: '',
status: '',
users: [
{
OrderId:'001',
userId: 'String',
user: {
email: 'string',
givenName: 'Name',
lastName: 'LastName',
phone: 'string',
},
},
],
},
the order is of type Order[] and users of type UserData[]
type Order
#model
#key(fields: ["organizationId", "id"])
#auth(
rules: []
) {
id: ID!
type: OrderType
status: OrderStatus
userConnections: [UserOrderConnection] #connection(keyName: "byOrder", fields: ["id"])
organizationId: ID!
}
type UserOrderConnection
#model
#key(fields: ["organizationId", "id"])
#key(name: "Order", fields: ["OrderId"], queryField: "userOrderByOrder")
#auth(
rules: []
) {
id: ID!
accepted: Boolean
OrderId: ID!
Order: Order #connection(fields: ["organizationId", "id"])
userId: ID!
user: UserData
}
Whenever I try to get the list of users per order :
let users = this.Order.users
it says that: users don't exist on type Order[], can anyone explain for me why.
Order is an array of objects, you need to get the first element like Order[0] then access .users
let users = this.Order[0].users
A good refresher might help here; How can I access and process nested objects, arrays or JSON?
Order is an Array containing objects. To access users you would need to access item at index [0] if it has property ?.users.
this.Order[0]?.users

Edit multiple objects in array using mongoose (MongoDB)

So I tried several ways, but I can't, I can modify several objects with the same key but I can't modify any with different keys, if anyone can help me is quite a complex problem
{
id: 123,
"infos": [
{ name: 'Joe', value: 'Disabled', id: 0 },
{ name: 'Adam', value: 'Enabled', id: 0 }
]
};
In my database I have a collection with an array and several objects inside which gives this.
I want to modify these objects, filter by their name and modify the value.
To give you a better example, my site returns me an object with the new data, and I want to modify the database object with the new object, without clearing the array, the name key never changes.
const object = [
{ name: 'Joe', value: 'Hey', id: 1 },
{ name: 'Adam', value: 'None', id: 1 }
];
for(const obj in object) {
Schema.findOneAndUpdate({ id: 123 }, {
$set: {
[`infos.${obj}.value`]: "Test"
}
})
}
This code works but it is not optimized, it makes several requests, I would like to do everything in one request, and also it doesn't update the id, only the value.
If anyone can help me that would be great, I've looked everywhere and can't find anything
My schema structure
new Schema({
id: { "type": String, "required": true, "unique": true },
infos: []
})
I use the $addToSet method to insert objects into the infos array
Try This :
db.collection.update({
id: 123,
},
{
$set: {
"infos.$[x].value": "Value",
"infos.$[x].name": "User"
}
},
{
arrayFilters: [
{
"x.id": {
$in: [
1
]
}
},
],
multi: true
})
The all positional $[] operator acts as a placeholder for all elements in the array field.
In $in you can use dynamic array of id.
Ex :
const ids = [1,2,..n]
db.collection.update(
//Same code as it is...
{
arrayFilters: [
{
"x.id": {
$in: ids
}
},
],
multi: true
})
MongoPlayGround Link : https://mongoplayground.net/p/Tuz831lkPqk
Maybe you look for something like this:
db.collection.update({},
{
$set: {
"infos.$[x].value": "test1",
"infos.$[x].id": 10,
"infos.$[y].value": "test2",
"infos.$[y].id": 20
}
},
{
arrayFilters: [
{
"x.name": "Adam"
},
{
"y.name": "Joe"
}
],
multi: true
})
Explained:
You define arrayFilters for all names in objects you have and update the values & id in all documents ...
playground

Adding element inside nested array in mongoose

Server Started at Port 3000...
{
_id: new ObjectId("61c707e9f4ff040a47d27c3f"),
username: 'adityaaryam',
password: '1234',
nameOfUser: 'Aditya Aryam',
emailOfUser: 'adityaaryam#gmail.com',
userAllLists: [
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70d915448262d1dca1a69")
},
{
name: 'Work',
items: [],
_id: new ObjectId("61c70d965448262d1dca1a70")
},
{
name: 'Home Work',
items: [],
_id: new ObjectId("61c70d9b5448262d1dca1a79")
},
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70e7f5448262d1dca1a84")
},
{
name: 'Play',
items: [],
_id: new ObjectId("61c7126a5448262d1dca1a9b")
},
{
name: 'Eat',
items: [],
_id: new ObjectId("61c71325b0219e6ce4f57990")
},
{
name: 'Walla',
items: [],
_id: new ObjectId("61c7197de9564390d506cbe9")
}
],
__v: 7
}
This is how my database looks like. I want to push new elements to "items" array which is nested inside the "userAllLists" array using mongoose. How do I implement this?
I have been trying findOneAndUpdate using $push but I am not able to achieve my desriable results.
My Schemas are as follows:
const itemSchema = {
name: String
};
const customListSchema ={
name:String,
items:[itemSchema]
};
const userSchema={
username: String,
password: String,
nameOfUser: String,
emailOfUser: String,
userAllLists: [customListSchema],
};
Thanks in Advance!
I think $push is the right way to push new elements to nested arrays, you didn't show the code you tried to see if it works or not, at all here is an example based on your schema
User.update({_id: "61c707e9f4ff040a47d27c3f", }, {
'$push': {
"userAllLists.$[].items": {name: "test item name"}
}
});
Note: $[] expressions will push the specified object inside all items arrays that exist in userAllLists
To push the item for only specific userAllLists object you can use the following syntax
User.update({_id: "61c707e9f4ff040a47d27c3f", "usersAllLists._id": "61c70d915448262d1dca1a69"}, {
'$push': {
"userAllLists.$.items": {name: "test item name"}
}
});
this will ensure to push the item object to the specified usersAllLists object which has this id 61c70d915448262d1dca1a69

Create Sequelize Query, Multiple Innerjoins and Wheres across multiple tables

I have created a successful mysql query that joins 2 tables that have foreign keys to each other. I got almost everything to work in Sequelize other than getting the user attached to the responses. My query does that successfully but I cannot understand how to get it.
This is my mysql query that works specifically gets the "users" that has the same id as the response "user_id"
SELECT *
FROM meetup_db.posts p
INNER JOIN meetup_db.responses r
INNER JOIN meetup_db.users u
WHERE p.id = r.post_id AND
r.user_id = u.id
This is my sequelize query that almost works but does not give me back the user in each response where user_id = id
const dbPostData = await Posts.findOne({
where: { id: req.params.id },
include: [
{ model: Users },
{
model: Responses,
include: {
model: Users,
where: { id: Responses.user_id }, //this is the line in question i need the user that has the same id as the Response.user_id
}
}
]
});
The sequelize correctlys outputs everything but the user, heres a sample output as you can see the response has Users listed inside but the users just show as [Object]
{
id: 1,
title: 'BBQ At My House!!',
description: 'Hey gang! Im having a BBQ at my house! I hope all can attend!!',
upvotes: 44,
location: '2113 Main St. Austin, TX.',
date_occuring: 2021-08-04T18:00:00.000Z,
created_at: 2021-08-06T04:42:01.000Z,
edited: false,
user_id: 1,
createdAt: 2021-08-06T04:42:01.000Z,
updatedAt: 2021-08-06T04:42:01.000Z,
User: {
id: 1,
username: 'Jennifer Wylan',
email: 'jwylan#gmail.com',
password: 'ewfchijwnsj',
image_url: '/assets/fake-pfp/fakeperson1.png'
},
Responses: [
{
id: 4,
response: 'Im in there like swimwear!',
user_id: 4,
post_id: 1,
createdAt: 2021-08-06T04:42:01.000Z,
updatedAt: 2021-08-06T04:42:01.000Z,
User: [Object] //these lines right here need to look like the above User: {} Object
},
{
id: 5,
response: 'weeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
user_id: 1,
post_id: 1,
createdAt: 2021-08-06T04:42:01.000Z,
updatedAt: 2021-08-06T04:42:01.000Z,
User: [Object] //these lines right here need to look like the above User: {} Object
}
],
}
I figured it out. So it worked already.
In my terminal the output of responses was showing the User key as [Object]
... Turns out when its like 3 tables deep the terminal just shows [Object] but it was actually there already, you also dont need the where: because it already looks for the foreign key

Push data to MongoDB without editing the whole entry in MEAN

So i've got a single page application running via MEAN Stack. I've got the following scheme/model for a Klausur (Klausur is german for exam, i want to manage exams).
var KlausurSchema = new Schema(
{
name: String,
semester: String,
krankmeldungen: [Number],
aufgaben: [{
name: String,
punkte: Number
}],
studenten: [{
matrnr: Number,
vorname: String,
nachname: String,
bewertung: [{
punkte: Number
}],
pversuch: String,
pvermerk: String,
freiverm: String,
labnr: Number,
porgnr: Number,
aenddat: String
}]
}
);
Multiple users can edit the entrys, otherwise i would just overwrite the entry. I want to have a table consisting of the "studenten" (students), is it possible to PUSH one student to my "studenten" without PUTTING (edit) the whole "Klausur", i.e. I want to push information to an array without overwriting the whole db entry!
Thanks in advance!
Please Check Docs
If you want to insert new students array. you can use below mentioned MongoDB query.
Using MongoDB
db.klausur.update(
{ name: "David" },
$addToSet: {
studenten: {
$each: [
{
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
},
{
matrnr: 124,
vorname: "ABCD",
nachname: "XYZA",
bewertung: [{
punkte: 1234
}]
}]
}
);
Using Mongoose
ModelName.update(
{ name: "David" },
$addToSet: {
studenten: {
$each: [
{
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
}]
}
);
you can also use $push instead of $addToSet. but $addToSet handle duplicates insertion issue. One more thing if you want to add single student object then just use above query without $each. for example
db.klausur.update(
{ name: "David" },
$addToSet: {
studenten: {
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
}
}
);
Pass an object to be updated to native mongoDB update query.
The pseudo query will be,
db.model.update(selector, objectToUpsert);
db.student.update(
{ name: "David" },
{
name: "Will",
marks: 75,
grade: A
},
{ upsert: true }
)
First find Klausur=exam say
Klausur.findOne({_id:sample_id}).exec(function (error, closure){
closure.students.push(newstudentobject);
closure.save();
})

Categories

Resources