0

I have Put A textfield in the ejs file under script tag

var message = document.getElementById("typing").value;

I want this variable Message having the keyword that need to be searched in the database (mongodb)

I can use NodeJs file to connect with db and find things i want

dbo.collection('Leave').find({$text:{$search : " those "}},{projection:{_id: 0, What_are_those:1}}).toArray(function(err, result) {.......});

but i am not ablle to connect it on with ejs and nodeJS. Basically the connection or binding between the two.

Aayushi Gupta
  • 369
  • 4
  • 18
  • Your question needs to clarify what are you exactly doing in EJS. Ideal place to fetch data from MongoDB would be controller, there on pass it to view layer. What MongoDB lib are you using? – ch4nd4n Jul 09 '18 at 11:37
  • var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/Chatbot_Project"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("Chatbot_Project"); dbo.collection('Leave').find({$text:{$search : " those "}},{projection:{_id: 0, What_are_those:1}}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }) }); this been by controller for finding from db – Aayushi Gupta Jul 09 '18 at 11:39
  • EJS file is basically javascript file only.. where i am making form for front end – Aayushi Gupta Jul 09 '18 at 11:40

1 Answers1

0

It is not very clear how you are posting the data, but assuming that you have search page posting to URL "/search" refer to the code below.

Ensure that your app is connected to MongoDb. Create a route (POST preferred) to which you can submit search term. Route uses mongoose model to query db and returns the mongodb document to ejs template.

const mongoUrl = REPLACE_WITH_MONGOURL;

const mongoose = require('mongoose');
mongoose.connect(mongoUrl);

mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB at: %s ', mongoUrl);
});

// assuming you post {"searchTerm": "SEARCH THIS STRING"} as body

app.post('/search', (req, res) => {
const searchTerm = req.body.searchTerm
model.find($text:{$search: searchTerm}).exec((err, doc) => {
    res.render('path/to.ejs', { msg: doc });
});
});

EJS should contain something like <%=msg.doc%>

ch4nd4n
  • 4,110
  • 2
  • 21
  • 43