質問

I have some codes in express+EJS,

1) in app.js , the mongo collection object is created,

app.locals.userCollection = db.get('userData');

2) in user.js express route file, I get the data from this DB connection and want to pass it to EJS to render,

exports.list = function(req, res){
   req.app.locals.userCollection.find({},function(err , returnValue){
       if(returnValue.length>0){          
          res.render('user', res.locals.returnValue);
       }
       return err;
       });

};

3) In user.ejs I try access it using

<div><script>
var test = <%- returnValue %>;

It gives me returnValue is not defined error.

May I know if i want to access returnValue[0].attr1, what I should code in route and EJS?

Regards Hammer

役に立ちましたか?

解決

You can try following:

In Node.js:

res.render('user', data: res.locals.returnValue);

In EJS:

<script type='text/javascript'>
  var rows =<%-JSON.stringify(data)%>
  alert(rows);
</script>


Update (as per questions asked in comments):

If you want to loop over the rows then you should not use JSON.stringify() since it converts your object into String and you may try doing the following (following code works if the data put by server is array object).

<script type='text/javascript'>
    <% data.forEach(function(dataRow, idxOfRow, orgnlAryObject) {
        // You can directly use the dataRow to get each row from the array Object `data`
        //alert(JSON.stringify(dataRow)); // <== You can try this
    }); %>
</script>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top