正如标题所示,在我的一个后端路由中使用findOne函数时出现以下错误:
/home/liam/Documents/aiRegister/node_modules/mongodb/lib/utils.js:123
process.nextTick(function() { throw err; });
^
TypeError: Cannot convert undefined or null to object
at db.collection.findOne (/home/liam/Documents/aiRegister/app/routes
/user_routes.js:14:16)
at handleCallback (/home/liam/Documents/aiRegister/node_modules/mongodb/lib/utils.js:120:56)
at /home/liam/Documents/aiRegister/node_modules/mongodb/lib/collection.js:1416:5
at handleCallback (/home/liam/Documents/aiRegister/node_modules/mongodb/lib/utils.js:120:56)
at /home/liam/Documents/aiRegister/node_modules/mongodb/lib/cursor.js:683:5
at handleCallback (/home/liam/Documents/aiRegister/node_modules/mongodb-core/lib/cursor.js:171:5)
at setCursorNotified (/home/liam/Documents/aiRegister/node_modules/mongodb-core/lib/cursor.js:515:3)
at /home/liam/Documents/aiRegister/node_modules/mongodb-core/lib/cursor.js:599:16
at queryCallback (/home/liam/Documents/aiRegister/node_modules/mongodb-core/lib/cursor.js:232:18)
at /home/liam/Documents/aiRegister/node_modules/mongodb-core/lib/connection/pool.js:469:18
这是我的代码:
//Get user
app.get('/user/:token', (req, res) => {
const details = {
'token': req.params.token
};
db.collection('users').findOne(details, (err, item) => {
if (err) {
res.send({
'error': 'An error has occurred'
});
} else {
delete item.token;
res.send(item);
}
});
});
我更新了npm和node以及所有已安装的软件包,没有运气。提前谢谢。
编辑:似乎错误来自'删除item.token;'因为事实证明,该文件不存在。然而,这引发了一个问题,即为什么文档不存在,即使它被添加(或者我认为。事实证明,添加用户的路径没有运行,但是我的前端正在返回成功。这是代码:
//Add user
app.post('/user', (req, res) => {
const user = {
email: req.body.email,
name: req.body.name,
token: req.body.token
};
const details = {
email: req.body.email
};
console.log("Adding user...");
db.collection('users').remove(details, (err, item) => {
if (err) {
res.send({
'error': 'An error has occurred'
});
} else {
console.log("User del...");
}
});
db.collection('users').insert(user, (err, result) => {
if (err) {
res.send({
'error': 'An error has occurred'
});
} else {
res.send(result.ops[0]);
console.log("User added");
}
});
});
在我的前端:
$.ajax({
type: "post",
url: "/api/user",
data: {
name: user["displayName"],
email: user["email"],
token: token
},
success: console.log("Success!")
});
我不知道为什么会这样。