Home>
Problem i am experiencing

The following data is stored in the database.

id name comment
1 curry test1
2 stew test2
3 curry test3


I search for the name of the dish (name) and display the result, but if there is only one like "stew", the search result can be displayed, but "curry" If there are two or more like, only one search result can be displayed.
In order to display all the search results, I changed fetch to fetchAll and tried to loop the part that displays the search results with for, but it did not work.
How can I display all the search results?

If the search result is 0 (for example, search for "miso soup"), the search will end and the page will not be updated.
I hope you can teach me how to solve it if possible.
Thank you.

Applicable source code
<body>
        
            <form method = "post" action = "/ hello/add" name = "test">
                
                    <span>Dish name:</span>
                    <input type = "text" name = "name" value = "<% = form.name%>">
                
                
                    </td><input type = "submit" value = "search">
                
            </form>
        
            
                    <% if (mydata! = null) {%>
                    <p><ul>
                        <li><%-mydata.id%></li>
                        <li><%-mydata.attributes.name%></li>
                        <li><%-mydata.attributes.comment%></li>
                    </ul></p>
                    <%}%>
            
</body>
var express = require ('express');
var router = express.Router ();
var mysql = require ("mysql");
var knex = require ("knex") ({
    dialect: "mysql",
    connection: {
        host: "localhost",
        user: "root",
        password: "",
        database: "db",
        charset: "utf8"
    }
});
var Bookshelf = require ("bookshelf") (knex);
var MyData = Bookshelf.Model.extend ({
    tableName: "mydata"
});
// MySQL configuration information
var mysql_setting = {
    host: "localhost",
    user: "root",
    password: "",
    database: "db"
};

// ADD
router.get ("/ add", (req, res, next) =>{
    var data = {
        form: {name: ""},
        mydata: null,
    }
    res.render ("hello/add", data);
});
router.post ('/ add', (req, res, next) =>{
        new MyData (). where ("name", "=", req.body.name) .fetch (). then ((collection) =>{
            var data = {
                form: req.body,
                mydata: collection,
            };
            res.render ("hello/add", data);
        })
});
module.exports = router;
  • Answer # 1

    If you execute a query and return multiple results, it is a two-layer object, so you can write it in the same way.

    [
      ["id": 1, "name": "curry", "comment": "soup curry"],
      ["id": 3, "name": "curry", "comment": "spice curry"]
    ]
    Since it is

    , the process to loop the object is necessary in the template or script.

Related articles