[英]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.让我先承认我对 MongoDB 和 Node.js 都很陌生。 I am trying to query a mongodb atlas db for a specific record in the collection.
我正在尝试查询 mongodb atlas db 以获取集合中的特定记录。 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.
该集合有 350K+ 文档,因此在获取所有文档时呈现 index.ejs 文件需要很长时间。 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.
理想情况下,index.ejs 页面上有字段,用户可以在其中输入参数值并单击提交以查询数据库并返回一条记录。 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.这是我正在使用的 server.js 代码。 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.
我假设 app.get 或类似的应该嵌入在 index.ejs 文件中,并且只在 server.js 代码中呈现 index.ejs 文件,但我没有任何运气。
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.这是 index.ejs 代码。
<!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.
我需要在 member.find 之后立即包含投影。 I'm still trying to figure out how to include this in the index.ejs file.
我仍在尝试弄清楚如何将其包含在 index.ejs 文件中。
app.get('/',function (req, res) {
member.find({Email: 'someone@gmail.com' },function(err, passes) {
if (err) return next(err)
res.render('index',{
passesList: passes
})
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.