Open In App

Mongoose Query.prototype.read() API

Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Query API.prototype.read() method of the Mongoose API is used on the Query objects. It allows us to tell the MongoDB from which node it should read the data. Using this method we can set one out of five different preferences to let MongoDB read the data. Let us understand the read() method using an example.

Preference:

  • primary: It is the default reading node. Query operation will produce an error if the primary node will not be available.
  • secondary: It is used to specify the secondary node preference. Query operation will produce an error if the secondary node will not be available.
  • primaryPreferred: It is used to specify the primaryPreferred node preference. In this preference, data is read from the primary if it is available else data is read from the secondary node.
  • secondaryPreferred: It is used to specify the secondaryPreferred node preference. In this preference, data is read from a secondary node if it is available else data is read from the primary node.
  • nearest: Query operations read the data from all the nearest nodes. However, it will include both primary and secondary nodes.

Syntax:

query.read( <preference> );

Parameters: This method accepts two parameters as discussed below:

  • preference: It is used to specify the read preference for MongoDB to read the data.
  • tags: It is used to specify optional tags for the query operation in the form of an array.

Return Value: This method returns the query object.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this:

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Example 1: In this example, we are illustrating the functionality of read() method. We have set the preferred node as the “primary” node.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
 
// Set Up the Database connection
 
let connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
let Customer = connectionObject.model(
    "Customer",
    new mongoose.Schema({
        name: String,
        address: String,
        orderNumber: Number,
    })
);
 
let query = Customer.find();
query.read("primary")
query.then((result) => {
    console.log("Result -", result);
}).catch((err) => {
    console.log(err);
});


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Result - [
    {
        _id: new ObjectId("639ede899fdf57759087a655"),
        name: 'Chintu',
        address: 'Indore',
        orderNumber: 0,
        __v: 0
    },
    {
        _id: new ObjectId("639ede899fdf57759087a653"),
        name: 'Aditya',
        address: 'Mumbai',
        orderNumber: 20,
        __v: 0
    },
    {
        _id: new ObjectId("63bcfcc2876922405349b69d"),
        name: 'Bhavesh',
        address: 'Mhow',
        orderNumber: 0,
        __v: 0
    }
]

Example 2: In this example, we are illustrating the functionality of the read() method. We have set the preferred node as a “secondary” node.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
 
// Set Up the Database connection
 
let connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
let Customer = connectionObject.model(
    "Customer",
    new mongoose.Schema({
        name: String,
        address: String,
        orderNumber: Number,
    })
);
 
let query = Customer.find({ name: "Chintu" });
query.read("secondary");
query.exec((error, result) => {
    if (error) {
        console.log("Error -", error);
    } else {
        console.log("Result -", result);
    }
});


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Result - [
    {
        _id: new ObjectId("639ede899fdf57759087a655"),
        name: 'Chintu',
        address: 'Indore',
        orderNumber: 0,
        __v: 0
    }
]

Reference: https://mongoosejs.com/docs/api/query.html#query_Query-read



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads