如何使用db.command()和NodeJS运行原始MongoDB操作



我已经为每个版本设置了新的Mongodb脚本,我正试图创建NodeJS实用程序,通过从文件夹中存在的.txt文件读取来运行脚本。

示例:在1.txt文件中,我有这个命令db.getCollection("users").createIndex({ name: 1 });,我想使用NodeJS运行

我的NodeJs程序如下

const { MongoClient } = require("mongodb");
const uri = "mongodb:uri";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db("employee");
// I want to run above script like here. How can i do it?
const result = await db.command({
dbStats: 1,
});
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);

我觉得你的.txt文件可能是.js文件。然后你会把它提供给你的mongodb实例,像这样mongo < yourFile.js

但如果由于某种原因这不能做到。

Eval

免责声明:请注意使用eval

所涉及的安全问题我觉得你要找的是eval。

您的代码可以简单地看起来像:

const { MongoClient } = require("mongodb");
const uri = "mongodb:uri";

MongoClient.connect(uri, function(err, db){
const dbo = db.db("test");
// Here you get your lines from your .txt file
let line_to_execute = 'dbo.collection("customers").findOne({}, (err, res)=>{console.log(res)});';
// Launch the execution of line_to_execute
eval(line_to_execute);
})

得到了解决方案,我们可以从。json文件中读取并像下面这样传递cmd。

let userNameIndex = {
createIndexes: "users",
indexes: [
{
key: { "name": 1 },
name: "nameIndex"
}
],
comment: "Prasad test"
};
eval(userNameIndex);
const result = await db.command(userNameIndex);
console.log(result);

最新更新