Javascript、MongoDB 上下文 -- TypeError:无法读取未定义的属性(读取“集合”)

问题描述 投票:0回答:1

我最近遇到了上述问题中提到的终端或命令提示符中弹出的错误。

显示的确切错误是:

const taskCollection = db.collection('tasks');
                              ^

TypeError: Cannot read properties of undefined (reading 'collection')
    at Command.<anonymous> (C:\Abc\xyz\Task-Manager-CLI-Project\index.js:50:31)
    at Command.listener [as _actionHandler] (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:494:17)
    at C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1296:65
    at Command._chainOrCall (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1193:12)
    at Command._parseCommand (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1296:27)
    at C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1082:27
    at Command._chainOrCall (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1193:12)
    at Command._dispatchSubcommand (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1078:25)
    at Command._parseCommand (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:1264:19)
    at Command.parse (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:910:10)

这是一个简单的任务管理器 CLI 项目。我已将 mongoDB 与我的项目连接,但仍然显示相同的错误,但我不明白错误在哪里?怎么解决呢 这是我的 2 个代码文件:

db.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';

//we have used MongoDB Node.js driver to connect js to MongoDB database.

const client = new MongoClient(uri)

let db;

async function connect(){
    try{
        await client.connect();
        db = client.db('task_manager_db'); 
        
        // it is selecting the database named 'taskmanager'. If the specified database does not exist, MongoDB will create it when you first write data to it.
        //now variable db holds the reference to 'taskmanager' database
        
        console.log('Connected to the database');
    } catch(err){
        console.log('Error connecting to the database...', err);
    }
}

function getDB(){
    return db;
}

module.exports = {connect, getDB};

index.js

//using commander.js library for the project
//commander.js library provides functions that can run the project on CLI mode.
//Which is the ultimate aim and learning behind the project: To create and run a project using CLI.

const program = require('commander');

//importing the functions from db.js
const {connect, getDB} = require('./db');

program
.version('1.0.0')
.description('Task Manager CLI')
//connecting MongoDB database (i.e. to the uri to be specific)
.action(connect());

//general structure of defining commands for CLI using commander.js library
// program
// .command('')
// .description('')
// .action(//function inside() => { });

//command to list all tasks --> list
program
.command('list')
.description('list of commands')
.action(async() => {
    //extract database from function
    const db = getDB();
    //refer to the collection in db
    const taskCollection = db.collection('tasks');

    try{
        const tasks = await taskCollection.find().toArray();
        console.log("Listing all the tasks:");
        tasks.forEach((task_) => {
            console.log(`- ${tasks.task_}`);
        });
    }catch(err){
        console.log("Error displaying tasks...");
    }

});

//command to add a task --> add <taskname>
program
.command('add <taskname>')
.description('Add a new task')
.action(async() => {
    const db = getDB();
    const taskCollection = db.collection('tasks');

    try{
        const result = await taskCollection.insertOne({ taskname });
        console.log(`New Task added: ${task} TaskID: ${result.insertedId}`);
    }catch(err){
        console.log("Error adding task...", err);
    }
});

//command to delete task --> delete <TaskId>
program
.command("delete <TaskId>")
.description("Delete a task")
.action(async() => {
    const db = getDB();
    const taskCollection = await db.collection('tasks');

    try{
        const result = await tasksCollection.deleteOne({ _id: new ObjectId(TaskId) });
        console.log(`Deleted Task (ID: ${TaskId}`);
    }catch(err){
        console.log("Error deleting a task...", err);
    }
});

program.parse(process.argv);
  1. 我尝试从 MongoDB 指南针更改 URI,甚至将其从 “New Connection” 重命名为 “Project1”,然后将 URI 复制到 db.js 文件。没成功。

  2. 我尝试将 URI 从 mongodb://localhost:27017 更改为 mongodb://localhost:27018 ORmongodb://localhost:27017mongodb://localhost:27017/Project1仍然不起作用。错误仍然出现。

预期输出是命令 list、add 、delete 应在命令提示符下运行并显示编码的 console.log() 输出或错误处理输出。相反,它说我的数据库task_manager_db的集合tasks未定义,因此无法读取其属性。

javascript mongodb typeerror uri mongodb-compass
1个回答
1
投票

由于

connect()
是一个异步函数,因此您应该在该函数本身内返回
db
并在
await
文件中使用
index.js
,如下所示:

db.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri)

let db;

async function connect(){
    try{
        await client.connect();
        db = client.db('task_manager_db'); 
        return db;
    } catch(err){
        console.log('Error connecting to the database...', err);
    }
}

module.exports = {connect};

index.js

const program = require('commander');
const {connect} = require('./db');

program
.version('1.0.0')
.description('Task Manager CLI');

program
.command('list')
.description('list of commands')
.action(async() => {
    const db = await connect();
    const taskCollection = db.collection('tasks');

    try{
        const tasks = await taskCollection.find().toArray();
        console.log("Listing all the tasks:");
        tasks.forEach((task_) => {
            console.log(`- ${tasks.task_}`);
        });
    }catch(err){
        console.log("Error displaying tasks...");
    }

});

program
.command('add <taskname>')
.description('Add a new task')
.action(async() => {
    const db = await connect();
    const taskCollection = db.collection('tasks');

    try{
        const result = await taskCollection.insertOne({ taskname });
        console.log(`New Task added: ${task} TaskID: ${result.insertedId}`);
    }catch(err){
        console.log("Error adding task...", err);
    }
});

program
.command("delete <TaskId>")
.description("Delete a task")
.action(async() => {
    const db = await connect();
    const taskCollection = await db.collection('tasks');

    try{
        const result = await tasksCollection.deleteOne({ _id: new ObjectId(TaskId) });
        console.log(`Deleted Task (ID: ${TaskId}`);
    }catch(err){
        console.log("Error deleting a task...", err);
    }
});

program.parse(process.argv);
© www.soinside.com 2019 - 2024. All rights reserved.