1

I'm trying to setting up a posts system where people will be able to comment and like. This is what I did right now

<!-- posts.ejs  -->
<% posts.forEach(function(task) { %>
    <%- include post.ejs %>
<% }) %>

When someone likes, I use socket like this

<!-- post.ejs -->
<script>
var socket = io('localhost:48001');
$('#like').on('click', function(event){
    var task = <% task._id %> 
    console.log(task);
    var liker = {
        pId: task ,
        usr: user._id,
        liker: 1
    };
    socket.emit('like', liker, function(response){
        if(response==true){
                //console.log("blue");
        }
    });
});

//server side
exports.like = (pId, usr) => {
Post.findOneAndUpdate({_id :pId}, {$inc : {'likers' : 1}}).exec();
};

My question is how can I know the id of the liked post (task._id is undefined)? If you have a better solution, let me know.

phenric
  • 307
  • 1
  • 8
  • 15

1 Answers1

0

You're not passing any values into your other template file.

<% posts.forEach(function(task) { %>
  <%- include post.ejs %>
<% }) %>

Needs to be more like:

<% posts.forEach(function(task) { %>
  <%- include('post.ejs', { task: task }) %>
<% }) %>

There may be more to it than that, but let me know if that works and, if not, I'll see if there's anything else to suggest.

Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60
  • Thx @matt for your response. It returns an _Error: ENOENT: no such file or directory,_ because it tries to open /views/posts/('post.ejs', {task: task})' as URL. How can I resolve it ? thx – phenric Dec 12 '17 at 18:19
  • Hmmm... I got my syntax straight from the ejs documentation. What version are you running? – Matt Fletcher Dec 12 '17 at 18:20
  • Wowwww, yes that's ancient :D For 1.0.0, I can't answer you, sorry. Probably possible with slightly different syntax, but not sure what – Matt Fletcher Dec 12 '17 at 18:25
  • Yeah I didn't realise how old it was :p When updated to version 2.5.7, I get the 'Error: Could not find include include file'. Any idea to fix it ? Thx – phenric Dec 12 '17 at 18:45
  • Seems like something to do with relative include paths: https://stackoverflow.com/questions/46309842/could-not-find-include-include-file – Matt Fletcher Dec 12 '17 at 18:47
  • Or try removing the `.ejs` extension from the include – Matt Fletcher Dec 12 '17 at 18:47
  • I doesn't change anything. The error seems to be an includeception :D – phenric Dec 12 '17 at 18:55
  • Finally, I succeed to resolve it with '<%- include('../posts/posts',{}) %>' and '<%- include('../posts/post', {task: task}) %>'. But when I like one post, the others are also liked. – phenric Dec 12 '17 at 19:08
  • Schweet! Really I'd need to see the contents of `task`, but perhaps that's for another question – Matt Fletcher Dec 12 '17 at 19:16
  • Thx for the help. I asked another question for the other problem. – phenric Dec 12 '17 at 20:49