Skip to content
Related Articles

Related Articles

Improve Article

How does Query.prototype.getPopulatedPaths() works in Mongoose ?

  • Last Updated : 12 Mar, 2021

The Query.prototype.getPopulatedPaths() function is used to get a list of paths to be populated by this query. An array of strings representing populated paths is passed as a parameter.
 

Syntax:  

Query.prototype.getPopulatedPaths()

Parameters: This function has one array parameter which is an array of strings representing populated paths.
Return Value: This function returns Query Object.

Mongoose Installation:

npm install mongoose

After installing the mongoose module, you can check your mongoose version in command prompt using the command. 



npm mongoose --version

After that, you can just create a folder and add a file for example, index.js as shown below.

Database: The sample database used here is shown below: 
 

Example 1:

index.js




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.find().populate({
    path: 'level2',
    populate: { path: 'level3' }
});
  
console.log("Populate:", query.getPopulatedPaths());

The project structure will look like this: 
 

Run index.js file using below command: 



node index.js

Output: 

Populate: [ 'level2', 'level2.level3' ]

Example 2:

index.js




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.find().populate({
    path: 'level2',
    populate: { path: 'level3' }
});
  
console.log("Populate:", query.getPopulatedPaths());
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});

The project structure will look like this: 
 

Run index.js file using below command: 

node index.js

Output: 

Server listening on PORT 3000
Populate: [ 'level2', 'level2.level3' ]

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :