I have the following two files and I'm trying to setup authentication but the incoming request comes up as undefined when I try to pass it through a function.
The code block
console.log(req.params)
Actually gives back the expected results, so if I were to send a request of...
http://localhost:5000/register/banana/john
...it would return
{ user: 'banana', password: 'john' }
but the following
await mongoUser.register(user, password);
I get
TypeError: Cannot read property 'toBSON' of undefined
If this happens to be a typescript specific problem, I apologize in advanced. I'm transitioning over from js so it's possible I'm not specifying a type somewhere.
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 () => { }, }
Error Message
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)
https://stackoverflow.com/questions/66608521/typescript-posting-coming-up-as-undefined-when-trying-to-connect-mongodb March 13, 2021 at 07:25AM
没有评论:
发表评论