Find Data in MongoDB Using Mongoose Express.js Routes and text Operator

suggest change

Setup

First, install the necessary packages with:

npm install express cors mongoose

Code

Then, add dependencies to server.js, create the database schema and the name of the collection, create an Express.js server, and connect to MongoDB:

var express = require('express');
var cors = require('cors'); // We will use CORS to enable cross origin domain requests.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var app = express();

var schemaName = new Schema({
    request: String,
    time: Number
}, {
    collection: 'collectionName'
});

var Model = mongoose.model('Model', schemaName);
mongoose.connect('mongodb://localhost:27017/dbName');

var port = process.env.PORT || 8080;
app.listen(port, function() {
    console.log('Node.js listening on port ' + port);
});

Now add Express.js routes that we will use to query the data:

app.get('/find/:query', cors(), function(req, res) {
    var query = req.params.query;

    // Mongoose 6+ dropped the query callback. find() is a thenable and
    // resolves to an array. An empty array means no documents matched.
    Model.find({
        'request': query
    }).then(function(result) {
        res.json(result);
    }).catch(function(err) {
        console.error(err);
        res.status(500).send(JSON.stringify({
            error : 'Error'
        }));
    });
})

Assume that the following documents are in the collection in the model:

{
        "_id" : ObjectId("578abe97522ad414b8eeb55a"),
        "request" : "JavaScript is Awesome",
        "time" : 1468710551
}
{
        "_id" : ObjectId("578abe9b522ad414b8eeb55b"),
        "request" : "JavaScript is Awesome",
        "time" : 1468710555
}
{
        "_id" : ObjectId("578abea0522ad414b8eeb55c"),
        "request" : "JavaScript is Awesome",
        "time" : 1468710560
}

The goal is to find every document whose request field contains the word "JavaScript".

Create a text index on "request" before running $text queries. Mongoose builds schema indexes when it connects if autoIndex is left on (the default). A $text query fails when that index does not exist yet. Add this next to the schema in server.js:

schemaName.index({ request: 'text' });

And replace:

Model.find({
    'request': query
}).then(function(result) {

With:

Model.find({
    $text: {
        $search: query
    }
}).then(function(result) {

$text and $search select documents in collectionName that contain at least one word from the search query.

Usage

To use this to find data, go to the following URL in a browser:

http://localhost:8080/find/<query>

Where <query> is the search query.

Example:

http://localhost:8080/find/JavaScript
[{
    _id: "578abe97522ad414b8eeb55a",
    request: "JavaScript is Awesome",
    time: 1468710551,
    __v: 0
},
{
    _id: "578abe9b522ad414b8eeb55b",
    request: "JavaScript is Awesome",
    time: 1468710555,
    __v: 0
},
{
    _id: "578abea0522ad414b8eeb55c",
    request: "JavaScript is Awesome",
    time: 1468710560,
    __v: 0
}]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents