passing user data to the client

I am using nodejs, express, mongoose and passport for authentication.
I have mongoose model named User which holds user data (a lot of data).
No, I want to create a route that renders index.jade and set the user data in the template.
My route is:

app.get('/something', function(req, res) {
    res.render('index', {
        user: req.user || {}
    });
});

My template:

doctype 5
html(lang="en")
    head
    body
        script(type='text/javascript')
            window.user = #{user};

I have two problems with the following:

  1. I don't want the client to get the whole User structure. I only need several attributes and that's all. I know from Java and from .NET that there is the term "Data Transfer Objects" that indicate an object that its purpose is to pass data to the client. What is the equivalent in node? What is the best practice in node of passing the client only the relevant data?

  2. The client need the user id in order to identify the user. I don't want to pass mongo original User document _id. What can I do? Should I need to encode the id somehow?

When you do res.render you actually don't send anything from the variables to your client except the variables you use in your template, so basically if you want to pass only the username of your user you can safely do ( with DRY improvement ) :

render = function(page, req, res) {
   res.render(page, { user: req.user ? req.user : {} });
};

app.get('/something', function(req, res) { render('index', req, res); });
app.get('/pageA', function(req, res) { render('pageA', req, res); });
app.get('/pageB', function(req, res) { render('pageB', req, res); });

OR

doctype 5
html(lang="en")
    head
    body
        script(type='text/javascript')
            | window.user = "#{user.username}";

If you want more complicated user object, you can always do :

doctype 5
html(lang="en")
    head
    body
        script(type='text/javascript')
            | window.user = { username: "#{user.username}", email: "#{user.email}" };

Basically this will NOT expose your user object to the client, just to the render function of your node viewer instance.

About the user id, you can use whatever other unique user property as username, email address, etc.

You could serialize the object for use on the client

doctype 5
html(lang="en")
    head
    body
        script(type='text/javascript')
            window.user = !={JSON.stringify(user)};

You could serialize on the server too

app.get('/something', function(req, res) {
    res.render('index', {
        user: JSON.stringify(req.user || {})
    });
});

and just assign it in the view

script(type='text/javascript')
    window.user = =#{user};