Remove element from Multiple MongoDB Array simultaneously - javascript

I am creating MERN Classroom where users can Create/Join classes using the class's unique Code. Whenever a user joins the classroom, class id gets pushed into the User's MongoDB document array (classesJoined) and the user id gets pushed into Classroom's MongoDB document array (classroomMembers)
Updated User's Document:
{
"_id": "62e7ef5f636d28247a21b1e7",
"name": "User One",
"email": "userone#mydomain.com",
"password": "encryptedPassword",
"classesJoined": [
"62e7f00e636d28247a21b20d",
"62e7f0a0636d28247a21b247"
]
}
Updated Classroom's Document:
{
"_id": "62e7f00e636d28247a21b20d",
"classroomName": "Class by User One",
"classroomCode": "9ljsgNqx",
"classroomMembers": [
"62e7ef5f636d28247a21b1e7"
]
}
When a user wants to leave the classroom, the classroom's ID should be removed from the User document as well as the User ID should also be removed from the Classroom Document.
To achieve this, I have tried this logic in my Express Server route:
try{
await Users.findByIdAndUpdate({_id: req.body.userID}, { $pull: { classesJoined: req.body.classID } })
await Classroom.findByIdAndUpdate({_id: req.body.classID}, { $pull: { classroomMembers: req.body.userID }
res.send("Class Removed")
})
} catch (error){
res.send("Error Occured")
}
POST Request Body Contains:
{
"userID": "62e7ef5f636d28247a21b1e7",
"classID": "62e7f00e636d28247a21b20d",
}
But the problem I am facing is that the User ID from Classroom.classroomMembers gets removed but in User Document, nothing is changing or showing an error. The classesJoined array keeps the same element.

Related

Insert to array if value is not present in more arrays

I am building a forum web app where user can like/dislike post of other users.
I have the following model, representing a Post:
[
{
_id:"0002253,
title:"My first post",
likes:[],
dislikes:[]
},
{
_id:"0002254,
title:"My second post",
likes:[],
dislikes:[]
},
{
_id:"0002255,
title:"My third post",
likes:[],
dislikes:[]
},
]
When a user sends a like or dislike, the latter's ID will be inserted into the corresponding array (like or dislike).
Each user can, for each post, insert only a like or a dislike (not both).
The query I used for the insert is the following:
let vote_result = await Poll.updateOne(
{
_id: poll_id,
$and: [
{ "likes": { $nin: [MY_ID] } },
{ "dislikes": { $nin: [MY_ID] }},
],
},
{
$addToSet: {
"likes": MY_ID,
},
},
So, theoretically, query should insert MY_ID in likes or dislikes array if and only if MY_ID is not present in either array.
The problem is that query still writes MY_ID in likes array (even if MY_ID is present in dislikes) and vice versa.
Let's suppose now I want to leave a 'Like' to a post:
Phase 1:
likes:[]
dislikes:[]
(I am able to like or dislike, it works.)
Phase 2:
likes: [MY_ID]
dislikes:[]
(I am not able send like again, it works, but I am still able to dislike - it should not allow me to vote again.)

MongoDB Get Field to Update a Value from Request Query

I have user object structured like this:
{
"id": "",
"username": "",
"name": "",
"bio": "",
"email": "",
"profileImg": "",
"phoneNumber": 0,
"messagingPoints": 0,
"funds": 0,
"inventoryId": "",
"lastLogin": "2022-02-23T03:27:13.535Z",
"isPrivate": false,
"messagesReceived": []
}
I want to be able to reach a patch endpoint to update any of these fields. For example, /api/user?id=userId&name=John, should be able to grab the field "name" and set it to John. /api/user/id=?id=userId&email=abc#gmail.com should grab the email field and set it to abc#gmail.com
I am struggling to find docs for MongoDB to accomplish this, so I'm wondering if it is not possible? Do I need a specific endpoint for each of these update operations (ex: /api/user/name?id=userId&value=John instead of /api/user?id=userId&name=John)?
If it is possible, how could I accomplish this? Thanks!
You can pass user ID in update filter. Also you can pass data in request body of the PUT request instead of query parameters.
app.put('/api/user', async (req, res) => {
const { id, ...data } = req.body;
// Filter out any invalid fields
// Update documents where id field is equal to value of id in request body
await collection.updateOne(
{ id },
{ $set: data }
);
return res.json({ data: "User updated" })
})

Can't query by ID as second parameter with AWS DataStore

I am total noob to AWS, DataStore, and DynamoDB. I can't figure out why this isn't working.
If I attempt query an object related to my users ID from Cognito this seems to work. If I console log I get an array with one User.
let profile = await DataStore.query(User, (u) =>
u.id('eq', user.attributes.sub)
);
// Returns [Model]
console.log('[LOADING USER DATA]', profile);
If I attempt query an object related to my users ID like this. (as recommended by the docs). I get undefined.
let profile = await DataStore.query(User, user.attributes.sub);
// Returns undefined
console.log('[LOADING USER DATA]', profile);
Dynamo Data looks fine to me but am I using the wrong primary key ID field or something?
{
"id": "929e6e62-e3a0-4b84-b050-72c53eebda93",
"_lastChangedAt": 1644433699,
"status": "Active",
"createdAt": "2022-02-09T19:08:18.548Z",
"name": "Test",
"orgs": [
"b6508155-f5cf-49b7-88d6-0e605677c4e4"
],
"_version": 1,
"role": "User",
"updatedAt": "2022-02-09T19:08:18.548Z",
"orgID": "b6508155-f5cf-49b7-88d6-0e605677c4e4",
"title": ""
}
What am I doing wrong?

Teams botframework send proactive message REST api

I Try to create new converation and send proactive message with teams bot (botfreamwork).
I used this document to do that.
I POST to : SERVICE_URL/v3/conversations/
BODY:
{
"bot": {
"id": BOT_ID
},
"members": [
{
"id": USER_ID
}
],
"channelData": {
"tenant": {
"id": TENANT_ID
}
}
}
BOT_ID - I put the app id of the bot (with a prefix of "28:")
USERֹ_ID - I copied the USER_ID from a message I received from the user (not in a proactive message)
TENANT_ID - I took the tenant id from the link of the teams
I get this error:
{
"error": {
"code": "BadSyntax",
"message": "Invalid user identity in provided tenant"
}
}
I made several attempts to change the user ID: I changed to a user that appears in ADD, I changed with a prefix of 29: and without a prefix of 29: - nothing helped, this error continues to appear.
What am I missing?

#Sequelize while adding retrieve all attributes

I would like to find a way to retrieve all my attributes while inserting in my Database.
models.association.build(associationParams)
.save()
.then(function(assoAdded){
return next(assoAdded);
}).catch(function(err){
// # TODO : implement error Handler
return next(err);
});
I got this :
{
"idAssoParente": null,
"id": 420,
"name": "a",
"email": "aa#aa.aa",
"updated_at": "2015-07-29T17:12:47.000Z",
"created_at": "2015-07-29T17:12:47.000Z"
}
But I want to return all my fields like description , phone , city from my database even if they are empty. Should I necessarily do a find after adding to get all my fields or does it exist a way to retrieve my fields without doing an other request ?
Thanks
In short, yes you would need to query your db to return the info. I just started using Sequelize but I found the following worked for me.
// if all the info you need is in your user
Users.build({req.body})
.save()
.then(function(newUser){
Users.find({where: {UserID: newUser.UserID}}).then(function(user){
//resolve your promise as you please.
});
// or if address info is in another model you can use eager loading.
Users.build({req.body})
.save()
.then(function(newUser){
Users.find({where: {UserID: newUser.UserID},
include: [{
model: address
}]
}).then(function(user){
//resolve your promise as you please.
});

Categories

Resources