简体   繁体   中英

How can I access express request object in Mongoose virtual get func

I tried to find this, but I could not find a solution which will answer my doubt.

I have a virtual mongoose property defined as :

  postSchema.virtual('permissions').get() => {
  });

What I am trying to achieve is fill this permissions property of string array type, with a list of permissions that user has on each post. This logic is derived through the owner user id, which is stored in the post mongo database and the user id present in the request object of express , which is coming from the requestor.

However, I realised that the request object is not available to virtual method:

postSchema.virtual('permissions').get((req) => {
    // req is null.
  });

Now, I do have a solution to fix this issue by making a find result to lean at service level.

 app.get('/api/posts', (req, res) => {
    PostModel.find({}, '-fbEmailAddress', { sort: { created_at: -1 } }).lean().exec(function (err, posts) {
        posts.array.forEach(element => {
            element.permissions = // write your permission logic here
        });
        res.send(posts);
    });
});

However, if I do so, it will not stop calling . any virtual properties that I have also defined. I loose the opportunity to manipulate firstname, lastname to fullname et. al.

Do you guys have any recommendations to resolve this in a nicest possible way, so that I have an access to the current user id coming in the request object?

Please note that it is an API, so I don't want to introduce any kind of session object.

Cheers

I think you should look at this module https://github.com/othiym23/node-continuation-local-storage

It allows to set context variables in your request middleware and then use them in all functions called from it, eg mongoose model handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM