I am trying to store conversations between two users using MongoDB and the following schema.
`var messageSchema = new Schema({
users: [
{
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
{
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}],
user_msgs: [
{
is_sender: {}, //A user in users
msg_body: String,
created: {
type: Date,
default: Date.now
}
}
]
});`
Is there a way to define is_sender so that it can only be a user from users?
Perhaps is_sender
shouldn't be a data type, but a function (which accepts a User and then runs a query to determine if that User is among the message users[]).
Perhaps you intend is_sender
to return an array of users. In that case, one way wouldbe to impement is_sender
as a function that runs a query to return the result (an array of Users).
I think there's some problems with this schema design. First of all, messageSchema
looks more like a conversationSchema
that contains lots of messages between two users. You probably want to have each message be a document. Also, the array type doesn't let you pick a length - you seem to want to restrict to a length of two in users
. Just have two user fields in that case. The users can be embedded docs with a reference to a user and an optional is_sender
field, or you can use the name of the user field itself to indicate who is the sender. I think a better schema would look like
var messageSchema = new Schema({
sender: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
recipient : {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
msg_body: String,
created: {
type: Date,
default: Date.now
}
})
though this is speculative since I don't know your full use case.