简体   繁体   中英

Sails.js - issues when trying to display model data

I have no problem retrieving all my models from the database and displaying them on page using this code:

index: function(req, res) {
    Applicant.find(function(err, applicants) {
        if (err) {
            return console.log(err);
        }else{
            res.view({
                apps: applicants
            });
        }
    });
} 

But, if I try to pull just one model and display it, my browser gets stuck on loading. This is the code that I use for pulling just one model:

display: function(req, res) {
    Applicant.find().where({id: 2}).done(function(err, appl) {
        if (err) {
            return console.log('HAI');
        }else{
            res.view({
                applicant: appl
            });
        }
    });
}

Likely, your browser is stuck because an error happens when you're trying to find an Applicant, and your code doesn't return any response in this case. So browser waits for response forever. Please try something like this

if (err) {
    console.log('HAI');
    return res.send(err, 500);
}

PS By the way, as of Sails v0.9, find() method will alwals return an array, even if only one record is found. If you want to find just one record by id, and expect single object in your view, you can use findOne() method.

.find() returns an array. You may be expecting a single applicant object.

Using appl[0] would solve this. Please note that Sails' Waterline ORM provides .findOne() for situations such as these. Here's more info on .findOne()

display: function(req, res) {
    Applicant.find().where({id: 2}).done(function(err, appl) {
        if (err) {
            return console.log('HAI');
        }else{
            res.view({
                applicant: appl[0]
            });
        }
    });
}

Or better yet...

display: function(req, res) {
    Applicant.findOne({id: 2}, function(err, appl) {
        if (err) {
            return console.log('HAI');
        }else{
            res.view({
                applicant: appl
            });
        }
    });
}

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