Reputation: 29
I'm a bit new to mongoDB and I'm trying to figure out if I should use MongoDB or to use the familiar SQL.
At first I really wanted to use MongoDB but it's going really slow, and I'm having a hard time how to design my DB and queries.
For instance: SQL
Let's say I have these tables:
User Table (Id, Name)
Group (Id, Name)
GroupInvites (UserId, GroupId, Status[A - active, I - invited])
And if I wanted to know if a player has and group invitations, it would be pretty easy the SELECT and UPDATE from the GroupInvites table.
MongoDB
But in MongoDB the GroupInvites is redundant, because we can have the Status in the group scheme.
const BetGroupSchema = mongoose.Schema({
name: {
type: String,
required: true
},
users: [{
userId: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'users',
required: true
},
userStatus: {
type: String,
required: true
}
}]
})
But now, if I wanted to SELECT only the groups that a specific user has an invite for, it would be much harder -
Group.find({
"users.userId": req.user._id,
"users.userStatus": "I"
})
The result of this would give a all group that have the UserID and all the groups that have UserStatus = 'I'.
And also I can't find a quick way to update the DB directly, If I wanted to update a specific user status to 'A'.
Maybe I got this wrong and someone can show me a good way to implement it in MongoDB or you think it would be better to go with SQL.
Upvotes: 0
Views: 102
Reputation: 768
I can understand as a beginner it becomes hard to do even a simple query well, if I would be at your place, I will do the query like this in a following way
1. Find query for a document nested in an array:
Group.find({users: {$elemMatch: {userId:req.user._id, userStatus:"I"}}})
2. Update query for a document nested in an array:
Group.update( { "name": "John","users.userId" : req.user._id },
{ "$set": { "users.$.userStatus": "A" } } )
Upvotes: 1