简体   繁体   中英

How to write to MongoDB database from EJS, Javascript?

I'm quite new in web/ server developing and I'm little bit confused about calling code from ejs. I have a table and I want to have button on every row. I want that after button click it will delete the specific item from MongoDB (I'm using Mongoose, NodeJS, Bootstrap Table, EJS). This is my code and the button

'<a class="remove" href="javascript:void(0)" title="Remove">',
        '<i class="fa fa-trash"></i>',
        '</a>' 

is the button to delete the row:

<table id="table">
    <thead>
      <tr>
        <th data-field="name">Device name</th>
        <th data-field="receivingKey">Receiving key</th>
        <th data-field="operate" data-formatter="operateFormatter" data-events="operateEvents"></th>
      </tr>
    </thead>
  </table>

  <script>
    var $table = $('#table');
    var data = <%- JSON.stringify(devices) %>;

    function operateFormatter(value, row, index) {
      return [
        '<a class="like" href="javascript:void(0)" title="Like">',
        '<i class="fa fa-heart"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="Remove">',
        '<i class="fa fa-trash"></i>',
        '</a>'
      ].join('')
    }

    window.operateEvents = {
      'click .like': function (e, value, row, index) {
        alert('You click like action, row: ' + JSON.stringify(row))
      },
      'click .remove': function (e, value, row, index) {
        // I want the delete action here.
      }
    }

    $(function () {
      $('#table').bootstrapTable({ data: data });
    });
  </script>
  <% } else { %>
  <div>You don't have any connected devices.</div>
  <% } %>
</div>

Problem is, that I don't know how to do it. I can write the code in nodejs backend, but I dont know how to call it from EJS. I made some attemps to use app.local to pass there the function, but it was throwing error due an async calling inside.

If you think this code is bad and I can use something different, let me also know. Thank you.

To clarify, ejs is not used for executing queries!

ejs is used to:

  • make html templates (such as header.ejs) that can be used on any page
  • pass variables from your server to html files

To do what you want, you will need to make a request from your javascript file to a specific route you have set on your app.js page, and then from your server, you can make the request to your db. Assuming you are using express, follow the steps below. If you aren't using express, let me know and I can walk you through setting it up.

First you will need the jQuery script at the bottom of your page:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 

<!-- make sure this script is above all your other scripts! -->

Next, make a script like this:

$.ajax({url:'/somePathHere', success: function(data) {

    //code you want to execute in the clients browser after the request is made goes here

}});

Finally, on your app.js page:

app.get('/somePathHere', function(req, res) {
    //make your call to the db here
}):

You can refer to this link:

http://dreamerslab.com/blog/en/write-a-todo-list-with-express-and-mongodb/

As ejs is used to make templates like header, footer, navigation for all pages. You can use javascript for generating HTML from EJS.

to this question the answer simply cannot give like this... What I can do is to guide you to a proper way to learn this technology

here you will see what is express and how to use it to configure a backed API..

here you will learn further about this full stack and how it is falling with every technology perfectly.. this is a Brad traversy's tutorial.. Also I learned from him..

So give it a go I'm saying this with trust ... just look at my reputation .. that's proof how much 've learned from him ..

cheers mate :)

Thank you all for help. I did not realized I can use POST method without rendering or redirecting to some page. I also discover that AJAX can send the POST request quite easily.

Backend:

const express = require('express');
const router = express.Router();

router.post('/remove-device', (req, res) => {
    //some code for deleting from mongo DB
    console.log('Success');
    res.send('ok');
});

module.exports = router;

Frontend:

<table id="table">
        <thead>
          <tr>
            <th data-field="name">Device name</th>
            <th data-field="receivingKey">Receiving key</th>
            <th data-field="operate" data-formatter="operateFormatter" data-events="operateEvents"></th>
          </tr>
        </thead>
      </table>

      <script>
        var $table = $('#table');
        var data = <%- JSON.stringify(devices) %>;

        function operateFormatter(value, row, index) {
          return [
            '<a class="like" href="javascript:void(0)" title="Like">',
            '<i class="fa fa-heart"></i>',
            '</a>  ',
            '<a class="remove" href="javascript:void(0)" title="Remove">',
            '<i class="fa fa-trash"></i>',
            '</a>'
          ].join('')
        }

        window.operateEvents = {
          'click .like': function (e, value, row, index) {
            alert('You click like action, row: ' + JSON.stringify(row))
          },
          'click .remove': function (e, value, row, index) {
            $.ajax({
              method: "POST",
              url: "/intr/remove-device",
              data: { deviceName: row.name },
            }).done(function (data) {});
          }
        }

        $(function () {
          $('#table').bootstrapTable({ data: data });
        });

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