lets0code
lets0code

Reputation: 163

how to seperate user acess to database in mongodb/mongoose

On the web app, I am currently working on, there is a button a user can click which will store emails into my MongoDB database. I also have a button where the user can click after they select a time range that displays all of the messages that are stored in the database for that time. The problem I am having is that when different users log in, they are able to see the other users messages when they click that button that retrieves the messages.

I am trying to figure out how can I make it so that a user can only see the messages that they have stored and not someone else's. Any ideas will be great.

report_schema

var mongoose = require('mongoose')

var sera = mongoose.Schema({
    isRead: Boolean,
    subject: String,
    from: String,
    receivedDateTime: Date,
    sentDateTime: Date
});

var user = mongoose.Schema({
    userID: {
        type: mongoose.Schema.Types.ObjectId,
        userName: String,
        ref: 'SERA'
    }
});


module.exports = mongoose.model("SERA", sera)

Upvotes: 1

Views: 52

Answers (1)

Simon Thiel
Simon Thiel

Reputation: 3285

You probably want to create another collection which contains user details and add a reference into below code to identify the user:

var mongoose = require('mongoose')

var sera = mongoose.Schema({
    isRead: Boolean,
    subject: String,
    from: String,
    receivedDateTime: Date,
    sentDateTime: Date,
    user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}      <-- this line
});

module.exports = mongoose.model("SERA", sera)

Upvotes: 1

Related Questions