简体   繁体   中英

submit query from index.ejs file to return a specific document from a mongodb collection

Let me preface this post by admitting I am very new to both MongoDB and Node.js. I am trying to query a mongodb atlas db for a specific record in the collection. I am able to get the entire list of documents but am having trouble using any kind of parameters. The collection has 350K+ documents so it takes extremely long to render the index.ejs file when getting all the documents. Ideally there would be fields on the index.ejs page where the user would enter the parameter values and click submit to query the database and return the one record. But for now, I just want to get this simpler code working and hardcode the query parameter values. Baby steps:)

Here is the server.js code I am using. I assume the app.get or similar should be embedded in the index.ejs file and only render the index.ejs file in the server.js code but I haven't had any luck.

const express = require('express');
const ejs = require('ejs');
const mongoose = require('mongoose');
const app = express();

app.set('view engine', 'ejs');

mongoose.connect('mongodb+srv://**********@*************/membershiptesting', { useNewUrlParser: true }, {useUnifiedTopology: true });

const memberSchema = {
       First: String,
       Last: String,
       email: String,
       PassAcct: String,
       ValidUntil: Date
    }
    
    const member = mongoose.model('passes',memberSchema);
    
    app.get('/', function (req, res) {
                member.find({},function(err, passes) {
                if (err) return next(err)
                res.render('index',{
                    passesList: passes
                })
            })
        })

app.listen(3000, function () {
    console.log('server is running')
});

This is the index.ejs code.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width=device-width, initial-scale=1">
        <title>Document</title>
    </head>    
    <h1>Members here</h1>
    <body>

        <%passesList.forEach(member => {%>
            <p><%= member.First %></p>
        <%})%>

    </body>
    
</html>

Thanks, Mark

I figured out how to include parameters. I needed to include the projection immediately following member.find. I'm still trying to figure out how to include this in the index.ejs file.

    app.get('/',function (req, res) {
                member.find({Email: 'someone@gmail.com' },function(err, passes) {
                if (err) return next(err)
                res.render('index',{
                    passesList: passes
                })
            })
        })

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