Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

node.js - Show MongoDB Query Result On ejs page

I have a router which returns a specefic user's information based on the unique Object_id from MongoDB. This works fine, and I get the correct results, but they are returned on a "blank" page as a JSON object. I want to simply fetch the result and render them on my ejs page. Here are my route:

//Here are my router.js:

router.get('/user/get:id', function (req, res) {
    MongoClient.connect(DBUri,{useUnifiedTopology: true }, function (err, db) {
        let dbo = db.db(DBName);
        const query = {_id: objectId(req.params.id)}
        dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
            if (err) throw err;
            res.send(resultTasks)
            db.close();
        });
    });
});


//Here are my file.ejs: 

<div class="card" v-for="post in filteredList">
     <a v-bind:href="'/user/get' + post.id">{{ post.name }}</a>
</div>

Im still new so I know this is properly basic. I guess I have to change the res.send to something else, but now sure how.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to loop over resultTasks in your ejs template, something like:

<% resultTasks.forEach((post) => { %> 
  <div class="card" v-for="post in filteredList">
     <a v-bind:href="/user/get/<%= post.id %>"><%= post.name %></a>
  </div>
<%}); %>

Also, you probably need to change send in your endpoint with

dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
    if (err) throw err;
    db.close();
    res.render('<path of your ejs file>', {
        resultTasks: resultTasks, // pass data from the server to the view
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...