I'm attempting to concatenate the mongodb query in a variable in node js depending on my condition. I'm unable to concatenate the mongodb attributes here. I've included the output I'm looking for below. I understand that the + icon only concatenates strings.
var query; query += db.collection('collection_name'); query += query.find(); if(project == true) { query +=query.project(project_parameter); } if(limit == true) { query += query.limit(); } // Output needed if i run the query variable db.collection('collection_name').find({id:1}).project({_id:1}).limit(10).toArray();
If these functions support chaining, then you can do something similar to this:
let query = db.collection('collection_name')
query = query.find()
if (project === true) {
query = query.project(project_parameter)
}
if (limit === true) {
query = query.limit()
}
This is because calling a function on db.colllection('collection_name') returns a modified object that you can keep calling functions on.