【问题标题】:Typescript posting coming up as undefined when trying to connect mongoDB尝试连接 mongoDB 时,打字稿发布未定义
【发布时间】:2021-03-13 10:06:05
【问题描述】:

我有以下两个文件,我正在尝试设置身份验证,但是当我尝试通过函数传递传入的请求时,它显示为未定义。

代码块

console.log(req.params)

实际上返回了预期的结果,所以如果我要发送一个请求......

http://localhost:5000/register/banana/john

...它会返回

{ 用户:'banana',密码:'john' }

但以下

await mongoUser.register(user, password);

我明白了

TypeError: Cannot read property 'toBSON' of undefined

如果这恰好是打字稿特定的问题,我提前道歉。我正在从 js 过渡,所以我可能没有在某处指定类型。

index.ts

import express, {Request, Response} from 'express';

const app = express();
const cors = require("cors");
const mongoUser = require("./mongoUser.ts");

/**
 * This is middleware
 */
app.use(cors());
app.use(express.json())

app.post("/register/:user/:password", async (req: Request, res: Response) => {
    try {
        console.log(req.params) //{ user: 'banana', password: 'john' }
        const {user, password} = await req.params;
        console.log(user); //banana
        console.log(password) //john
      
        await mongoUser.register(user, password); //error within

        res.json("Successfully registered!");
    } catch (err) {
        console.error(err);
    }
})

app.listen(5000, () => {
    console.log("server has started on port 5000");
});

mongoUser.ts

export {};
const {MongoClient} = require('mongodb');
const credentials = require('./mongoAuth.json');
const uri = `${credentials.client}/${credentials.database}?retryWrites=true&w=majority`
const mongoClient = new MongoClient(uri);


module.exports = {

    validator: async () => {

    },

    login: async () => {

    },

    register: async (user: string, pass: string) => {
        await mongoClient.connect();

        await mongoClient.db(`${credentials.database}`).collection(`${credentials.collection[0]}`).updateOne(
            {
                $push: {
                    username: user,
                    password: pass
                }
            }
        )

        mongoClient.logout();
    },

    allUsers: async () => {

    },

}

错误信息

TypeError: Cannot read property 'toBSON' of undefined
    at hasAtomicOperators (C:\Users\Home\WebstormProjects\sentimentalAnalysis\node_modules\mongodb\lib\utils.js:813:28)
    at new UpdateOneOperation (C:\Users\Home\WebstormProjects\sentimentalAnalysis\node_modules\mongodb\lib\operations\update_one.js:13:10)
    at Collection.updateOne (C:\Users\Home\WebstormProjects\sentimentalAnalysis\node_modules\mongodb\lib\collection.js:764:5)
    at C:\Users\Home\WebstormProjects\sentimentalAnalysis\src\server\mongoUser.ts:21:100
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\Home\WebstormProjects\sentimentalAnalysis\src\server\mongoUser.ts:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

【问题讨论】:

    标签: javascript node.js mongodb typescript express


    【解决方案1】:

    嗯,我注意到的第一件事是在await mongoUser.register(username, password); //error within 行的第一个sn-p 中,您使用username 作为变量,而上面您只定义了userpassword..

    这可能是问题吗?

    【讨论】:

    • 我确实确保传递的参数是正确的,但我没有在stackoverflow帖子中完全更改它,我现在将其更改我仍然有同样的问题
    • 我想通了,很抱歉浪费您的时间。
    【解决方案2】:

    在创建新的 Mongo 客户端实例时尝试强制统一拓扑,就像这样 const mongoClient = new MongoClient(uri, { useUnifiedTopology: true }); 这里是更多详细信息的链接 - https://jira.mongodb.org/browse/NODE-2091

    【讨论】:

    • 我想通了,很抱歉浪费您的时间。
    【解决方案3】:

    所以,很抱歉浪费了大家的时间,但我想通了。基本上,我想添加一个新用户,并且我正在使用另一个项目中的代码,它通过更新当前用户来添加一个条目。所以我当前的代码是错误的,因为

    1. 我使用的是 updateOne 而不是 insertOne
    2. 即使我确实想使用 updateOne,我也需要先定义一个过滤器,这就是为什么我的 ide 甚至没有分别将 $push 标记为 filter: 和 update: 标签的原因

    以下是我所做的更改

    mongoUser.ts

        register: async (user: string, pass: string) => {
            await mongoClient.connect();
    
            console.log("This is the user")
            console.log(user);
    
    
            await mongoClient.db(`${credentials.database}`).collection(`${credentials.collection[1]}`).insertOne(
                {
                    username: user,
                    password: pass
                }
            )
    
            mongoClient.logout();
        },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多