visualight
visualight

Reputation: 155

NodeJS : How to get data into views?

How i can get single data from model in the view ?

here is my controller :

router.get('/edit/:id', isAuthenticated, function(req, res)
    {
        File.find({_id:req.params.id}, function(err, files){

            if(err) 
                return console.error(err.stack);

            if(!files) 
                return console.error("File not found!");

            res.render('edit', { user: req.user, files: files});

        });

    });

You see, i fetch a unique data based on his ID

In my view, i get the data (files) like this :

each file in files
            div.row
                div.col-sm-6.col-md-6
                    form(action='/edit', class='form-upload', enctype='multipart/form-data', method='post')
                        .form-group
                            label(class='control-label') Position
                            input(type='text', name='order', class='form-control input-lg', value='#{file.order}')
                        .form-group
                            label(class='control-label') Nom du fichier
                            input(type='text', name='name', class='form-control input-lg', value='#{file.name}')
                        .form-group
                            label(class='control-label') Délai
                            input(type='text', name='delay', class='form-control input-lg', value='#{file.delay}')

Question : How to avoid each file in files and call directly files.name for example ?

Upvotes: 0

Views: 668

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

If you want your model to return an object instead of an array, use findOne instead.

router.get('/edit/:id', isAuthenticated, function(req, res) {
    File.findOne({
        _id: req.params.id
    }, function(err, file) {
        if (err)
            return console.error(err.stack);
        if (!file)
            return console.error("File not found!");
        res.render('edit', {
            user: req.user,
            file: file
        });
    });
});

Just to add, element(class="className") can be shortened to element.className

.row
    .col-sm-6.col-md-6
        form.form-upload(action='/edit', enctype='multipart/form-data', method='post')
            .form-group
                label.control-label Position
                input.form-control.input-lg(type='text', name='order', value='#{file.order}')
            .form-group
                label.control-label Nom du fichier
                input.form-control.input-lg(type='text', name='name', value='#{file.name}')
            .form-group
                label.control-label Délai
                input.form-control.input-lg(type='text', name='delay', value='#{file.delay}')

Upvotes: 1

Related Questions