Saturday 13 May 2017

How can I check and query a document using mongoose?

I have an userSchema and fileSchema. In file schema, I have fields like owner(ref: user) and field hasAccess(ref: user) - array of users something like this:

const FileSchema = new Schema({
    filename: String,
    filesize: Number,
    owner: {type: Schema.Types.ObjectId, ref: 'User'},
    hasAccess: [{type: Schema.Types.ObjectId, ref: 'User'}],
    createdAt: {type: Date, default: Date.now}
});


const UserSchema = new Schema({
    username: String,
    password: String,
    passphrase: String,
    files: [{type: Schema.Types.ObjectId, ref: 'File' }],
    createdAt: {type: Date, default: Date.now}
});

I have a route:

.get('/file/:id', [isLoggedIn], function (req, res) {
            const user = req.user,
                fileId = req.params.id;
            File
                .findOne({_id: fileId})
                .populate('hasAccess')
                .exec(function (err, file) {
                    if (err) {
                        console.log(err);
                        return res.redirect("/error");
                    }
                    //check here if user is owner OR user in hasAccess array 
                });
        })

There I query a file by Id and then check if a user has rights to this file. To check if user it's enough file.owner == user._id But what about hasAccess field should I iterate each object and compare it with current user id? Or is it possible make a query without any further comparison?



via Haygo

No comments:

Post a Comment