【发布时间】: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