Is there a way to send function context to model in nodejs mongoose?How is Node.js inherently faster when it still relies on Threads internally?Is there a way to get version from package.json in nodejs code?Binding Mongoose models save method inside async.auto (NodeJs)Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?Accessing Express.js request context in Mongoose modelsMongoose dynamic models, cannot use populate()Best practice to handle errors in Mongoose's post hooksMongoose pass req object to middlewareHow to access one model Schema in another model mongoose databaseGet model count in Mongoose pre hooks

Can i enter UK for 24 hours from a Schengen area holding an Indian passport?

(Familier) (Populaire) (Argot) - what's the difference?

Is it possible to transpose samples (in cents) from minor to major?

Why don't we have a weaning party like Avraham did?

How did Aragorn, Legolas, and Gimli know what Uruk-hai were?

I just entered the USA without passport control at Atlanta airport

Text alignment in tikzpicture

I found a password with hashcat, but it doesn't work

How did Gollum enter Moria?

What is this plant I saw for sale at a Romanian farmer's market?

Am I legally required to provide a (GPL licensed) source code even after a project is abandoned?

How do internally carried IR missiles acquire a lock?

How to remove this inheritance-related code smell?

Justifying Affordable Bespoke Spaceships

macOS: How to take a picture from camera after 1 minute

Counterfeit checks were created for my account. How does this type of fraud work?

How does join() produce different results depending on the arguments?

What is the highest voltage from the power supply a Raspberry Pi 3 B can handle without getting damaged?

Cut the gold chain

"Correct me if I'm wrong"

What triggered jesuits' ban on infinitesimals in 1632?

Traversing Latin America & Caribbean: A Cryptic Journey

What does this Swiss black on yellow rectangular traffic sign with a symbol looking like a dart mean?

Why is it easier to balance a non-moving bike standing up than sitting down?



Is there a way to send function context to model in nodejs mongoose?


How is Node.js inherently faster when it still relies on Threads internally?Is there a way to get version from package.json in nodejs code?Binding Mongoose models save method inside async.auto (NodeJs)Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?Accessing Express.js request context in Mongoose modelsMongoose dynamic models, cannot use populate()Best practice to handle errors in Mongoose's post hooksMongoose pass req object to middlewareHow to access one model Schema in another model mongoose databaseGet model count in Mongoose pre hooks






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I need to implement pre hooks in mongoose that are based on the id of the user that does the request.



I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks.



let writePermissionCondition = async function(next) 
let ctx = getCurrentContext();
next();



As I can't send the current context in the mongoose model, I can't access the userId that does the actual request.



Edit: a little more info on the architecture and what I'm trying to achieve



1) The user makes a request to the service (listening to events. ex: user/create, user/delete, user/find, etc)



2) The event calls a CRUD function



3) The Model used in the CRUD has ReadPermission and WritePermission middlewares (hooks)



4) The ReadPermission and WritePermission verifies the user that makes the request if, in fact, has permissions to read or write. This is the step where I need to know what user tried to access that Model.



I might be wrong, and the permissions should be implemented in the controller and not in the model.










share|improve this question
























  • could you add a sample code of your getCurrentContext() implementation? This will be helpful in order to have a good answer for your problem.

    – lifeisfoo
    Mar 25 at 12:58











  • you initial question was about a mongoose problem "I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks" and two answers were given. After you edit, this question has become about a suggested architecture: "a little more info on the architecture and what I'm trying to achieve...permissions should be implemented in the controller and not in the model". If you have an architecture-related doubt create another question and keep this question about the original problem. Btw: softwareengineering.stackexchange.com/help/on-topic

    – lifeisfoo
    Mar 26 at 11:48

















0















I need to implement pre hooks in mongoose that are based on the id of the user that does the request.



I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks.



let writePermissionCondition = async function(next) 
let ctx = getCurrentContext();
next();



As I can't send the current context in the mongoose model, I can't access the userId that does the actual request.



Edit: a little more info on the architecture and what I'm trying to achieve



1) The user makes a request to the service (listening to events. ex: user/create, user/delete, user/find, etc)



2) The event calls a CRUD function



3) The Model used in the CRUD has ReadPermission and WritePermission middlewares (hooks)



4) The ReadPermission and WritePermission verifies the user that makes the request if, in fact, has permissions to read or write. This is the step where I need to know what user tried to access that Model.



I might be wrong, and the permissions should be implemented in the controller and not in the model.










share|improve this question
























  • could you add a sample code of your getCurrentContext() implementation? This will be helpful in order to have a good answer for your problem.

    – lifeisfoo
    Mar 25 at 12:58











  • you initial question was about a mongoose problem "I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks" and two answers were given. After you edit, this question has become about a suggested architecture: "a little more info on the architecture and what I'm trying to achieve...permissions should be implemented in the controller and not in the model". If you have an architecture-related doubt create another question and keep this question about the original problem. Btw: softwareengineering.stackexchange.com/help/on-topic

    – lifeisfoo
    Mar 26 at 11:48













0












0








0








I need to implement pre hooks in mongoose that are based on the id of the user that does the request.



I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks.



let writePermissionCondition = async function(next) 
let ctx = getCurrentContext();
next();



As I can't send the current context in the mongoose model, I can't access the userId that does the actual request.



Edit: a little more info on the architecture and what I'm trying to achieve



1) The user makes a request to the service (listening to events. ex: user/create, user/delete, user/find, etc)



2) The event calls a CRUD function



3) The Model used in the CRUD has ReadPermission and WritePermission middlewares (hooks)



4) The ReadPermission and WritePermission verifies the user that makes the request if, in fact, has permissions to read or write. This is the step where I need to know what user tried to access that Model.



I might be wrong, and the permissions should be implemented in the controller and not in the model.










share|improve this question
















I need to implement pre hooks in mongoose that are based on the id of the user that does the request.



I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks.



let writePermissionCondition = async function(next) 
let ctx = getCurrentContext();
next();



As I can't send the current context in the mongoose model, I can't access the userId that does the actual request.



Edit: a little more info on the architecture and what I'm trying to achieve



1) The user makes a request to the service (listening to events. ex: user/create, user/delete, user/find, etc)



2) The event calls a CRUD function



3) The Model used in the CRUD has ReadPermission and WritePermission middlewares (hooks)



4) The ReadPermission and WritePermission verifies the user that makes the request if, in fact, has permissions to read or write. This is the step where I need to know what user tried to access that Model.



I might be wrong, and the permissions should be implemented in the controller and not in the model.







node.js mongoose






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 20:22







ktln2003

















asked Mar 25 at 6:53









ktln2003ktln2003

12




12












  • could you add a sample code of your getCurrentContext() implementation? This will be helpful in order to have a good answer for your problem.

    – lifeisfoo
    Mar 25 at 12:58











  • you initial question was about a mongoose problem "I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks" and two answers were given. After you edit, this question has become about a suggested architecture: "a little more info on the architecture and what I'm trying to achieve...permissions should be implemented in the controller and not in the model". If you have an architecture-related doubt create another question and keep this question about the original problem. Btw: softwareengineering.stackexchange.com/help/on-topic

    – lifeisfoo
    Mar 26 at 11:48

















  • could you add a sample code of your getCurrentContext() implementation? This will be helpful in order to have a good answer for your problem.

    – lifeisfoo
    Mar 25 at 12:58











  • you initial question was about a mongoose problem "I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks" and two answers were given. After you edit, this question has become about a suggested architecture: "a little more info on the architecture and what I'm trying to achieve...permissions should be implemented in the controller and not in the model". If you have an architecture-related doubt create another question and keep this question about the original problem. Btw: softwareengineering.stackexchange.com/help/on-topic

    – lifeisfoo
    Mar 26 at 11:48
















could you add a sample code of your getCurrentContext() implementation? This will be helpful in order to have a good answer for your problem.

– lifeisfoo
Mar 25 at 12:58





could you add a sample code of your getCurrentContext() implementation? This will be helpful in order to have a good answer for your problem.

– lifeisfoo
Mar 25 at 12:58













you initial question was about a mongoose problem "I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks" and two answers were given. After you edit, this question has become about a suggested architecture: "a little more info on the architecture and what I'm trying to achieve...permissions should be implemented in the controller and not in the model". If you have an architecture-related doubt create another question and keep this question about the original problem. Btw: softwareengineering.stackexchange.com/help/on-topic

– lifeisfoo
Mar 26 at 11:48





you initial question was about a mongoose problem "I can't access the initial function context (userId, permissions, etc) and use it in mongoose pre hooks" and two answers were given. After you edit, this question has become about a suggested architecture: "a little more info on the architecture and what I'm trying to achieve...permissions should be implemented in the controller and not in the model". If you have an architecture-related doubt create another question and keep this question about the original problem. Btw: softwareengineering.stackexchange.com/help/on-topic

– lifeisfoo
Mar 26 at 11:48












2 Answers
2






active

oldest

votes


















0














Set it to global var and use it on mongoose operation



let writePermissionCondition = async function(next) 
let ctx = getCurrentContext();
global.ctx = ctx
next();



Now you can access global.ctx anywhere in the application.






share|improve this answer


















  • 1





    I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

    – ktln2003
    Mar 25 at 12:06











  • global data of each request will be managed differently, so there is no problem. global is not a common place like database.

    – Thamaraiselvam
    Mar 25 at 12:10


















0














Mongoose provides many useful tools for solving complex situations like your question.



In your case you can user mongoose virtuals:




Virtuals are document properties that you can get and set but that do not get persisted to MongoDB.




You can start trying with a simple implementation like this:



yourSchema.virtual('context').
get(function() return this.__context; ).
set(function(ctx)
this.__context = ctx;
);


In this way you can call getCurrentContext(); where the context is available (e.g. during express req/res flow) and save it the model you've retrieved.



Example flow (pseudocode):



const user = User.get(req.id)
const context = getCurrentContext();
user.context = context;
//... save/update...


Now, when the user will be saved/updated, and your pre hooks are called, your validation code can access the context variable attached to retrieve your data.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55332573%2fis-there-a-way-to-send-function-context-to-model-in-nodejs-mongoose%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Set it to global var and use it on mongoose operation



    let writePermissionCondition = async function(next) 
    let ctx = getCurrentContext();
    global.ctx = ctx
    next();



    Now you can access global.ctx anywhere in the application.






    share|improve this answer


















    • 1





      I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

      – ktln2003
      Mar 25 at 12:06











    • global data of each request will be managed differently, so there is no problem. global is not a common place like database.

      – Thamaraiselvam
      Mar 25 at 12:10















    0














    Set it to global var and use it on mongoose operation



    let writePermissionCondition = async function(next) 
    let ctx = getCurrentContext();
    global.ctx = ctx
    next();



    Now you can access global.ctx anywhere in the application.






    share|improve this answer


















    • 1





      I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

      – ktln2003
      Mar 25 at 12:06











    • global data of each request will be managed differently, so there is no problem. global is not a common place like database.

      – Thamaraiselvam
      Mar 25 at 12:10













    0












    0








    0







    Set it to global var and use it on mongoose operation



    let writePermissionCondition = async function(next) 
    let ctx = getCurrentContext();
    global.ctx = ctx
    next();



    Now you can access global.ctx anywhere in the application.






    share|improve this answer













    Set it to global var and use it on mongoose operation



    let writePermissionCondition = async function(next) 
    let ctx = getCurrentContext();
    global.ctx = ctx
    next();



    Now you can access global.ctx anywhere in the application.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 25 at 7:04









    ThamaraiselvamThamaraiselvam

    4,79063150




    4,79063150







    • 1





      I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

      – ktln2003
      Mar 25 at 12:06











    • global data of each request will be managed differently, so there is no problem. global is not a common place like database.

      – Thamaraiselvam
      Mar 25 at 12:10












    • 1





      I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

      – ktln2003
      Mar 25 at 12:06











    • global data of each request will be managed differently, so there is no problem. global is not a common place like database.

      – Thamaraiselvam
      Mar 25 at 12:10







    1




    1





    I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

    – ktln2003
    Mar 25 at 12:06





    I could. But let's say you have 100 concurrent users that use this function. I need to know to userId of the user making the request when I call 'writePermissionCondition'

    – ktln2003
    Mar 25 at 12:06













    global data of each request will be managed differently, so there is no problem. global is not a common place like database.

    – Thamaraiselvam
    Mar 25 at 12:10





    global data of each request will be managed differently, so there is no problem. global is not a common place like database.

    – Thamaraiselvam
    Mar 25 at 12:10













    0














    Mongoose provides many useful tools for solving complex situations like your question.



    In your case you can user mongoose virtuals:




    Virtuals are document properties that you can get and set but that do not get persisted to MongoDB.




    You can start trying with a simple implementation like this:



    yourSchema.virtual('context').
    get(function() return this.__context; ).
    set(function(ctx)
    this.__context = ctx;
    );


    In this way you can call getCurrentContext(); where the context is available (e.g. during express req/res flow) and save it the model you've retrieved.



    Example flow (pseudocode):



    const user = User.get(req.id)
    const context = getCurrentContext();
    user.context = context;
    //... save/update...


    Now, when the user will be saved/updated, and your pre hooks are called, your validation code can access the context variable attached to retrieve your data.






    share|improve this answer



























      0














      Mongoose provides many useful tools for solving complex situations like your question.



      In your case you can user mongoose virtuals:




      Virtuals are document properties that you can get and set but that do not get persisted to MongoDB.




      You can start trying with a simple implementation like this:



      yourSchema.virtual('context').
      get(function() return this.__context; ).
      set(function(ctx)
      this.__context = ctx;
      );


      In this way you can call getCurrentContext(); where the context is available (e.g. during express req/res flow) and save it the model you've retrieved.



      Example flow (pseudocode):



      const user = User.get(req.id)
      const context = getCurrentContext();
      user.context = context;
      //... save/update...


      Now, when the user will be saved/updated, and your pre hooks are called, your validation code can access the context variable attached to retrieve your data.






      share|improve this answer

























        0












        0








        0







        Mongoose provides many useful tools for solving complex situations like your question.



        In your case you can user mongoose virtuals:




        Virtuals are document properties that you can get and set but that do not get persisted to MongoDB.




        You can start trying with a simple implementation like this:



        yourSchema.virtual('context').
        get(function() return this.__context; ).
        set(function(ctx)
        this.__context = ctx;
        );


        In this way you can call getCurrentContext(); where the context is available (e.g. during express req/res flow) and save it the model you've retrieved.



        Example flow (pseudocode):



        const user = User.get(req.id)
        const context = getCurrentContext();
        user.context = context;
        //... save/update...


        Now, when the user will be saved/updated, and your pre hooks are called, your validation code can access the context variable attached to retrieve your data.






        share|improve this answer













        Mongoose provides many useful tools for solving complex situations like your question.



        In your case you can user mongoose virtuals:




        Virtuals are document properties that you can get and set but that do not get persisted to MongoDB.




        You can start trying with a simple implementation like this:



        yourSchema.virtual('context').
        get(function() return this.__context; ).
        set(function(ctx)
        this.__context = ctx;
        );


        In this way you can call getCurrentContext(); where the context is available (e.g. during express req/res flow) and save it the model you've retrieved.



        Example flow (pseudocode):



        const user = User.get(req.id)
        const context = getCurrentContext();
        user.context = context;
        //... save/update...


        Now, when the user will be saved/updated, and your pre hooks are called, your validation code can access the context variable attached to retrieve your data.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 13:23









        lifeisfoolifeisfoo

        7,48034472




        7,48034472



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55332573%2fis-there-a-way-to-send-function-context-to-model-in-nodejs-mongoose%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해