Recommand · October 22, 2021 0

How to execute a string as a mongo query in Node JS. Here are my sketches. db.eval error is not a function

I saw somewhere to do something you need to do something with db.eval, but node throw error that eval is not a function. I wanna execute string as mongo query. It DYNAMIC

const mongoClient = require("mongodb");
const url = "someurl";
const mongoClient = new MongoClient(url)

async function run() {
    try {
        await mongoClient.connect();
        const db = mongoClient.db("somedb");
        
       
        var query = "db.getCollection('somecollection').find().limit(1)";
        db.eval('function(){ return ' + query + '.toArray(); }', function (err, res) {
            console.log(res);
        });

    }catch(err) {
        console.log(err);
    } finally {
        await mongoClient.close();
    }
}
run();