检查mongodb数据库中是否已经存在用户



我试图检查一个用户是否已经存在于注册表单的数据库中。如果用户已经存在,那么api路由应该返回一条消息"用户已经存在";但是如果用户不存在,那么新用户的数据应该被添加到mongodb数据库中。在下面的代码中,它总是返回"User already exists"即使它们不存在于数据库中。

import { connectToDatabase } from '../../../lib/db';
import { hashPassword } from '../../../lib/auth';
export default async function handler(req, res) {
if (req.method === 'POST') {
const client = await connectToDatabase();
const db = client.db();
const data = req.body;
const { email, password } = data;
const existingUser = db.collection('users').findOne({ email: email });
if (existingUser) {
res.json({ message: 'User already exists', existingUser: existingUser });
client.close();
return;
} //checks if user already exists
if (
!email ||
!email.includes('@') ||
!email.includes('.') ||
!password ||
password.trim().length < 7
) {
res.status(422).json({ message: 'Invalid email or password' });
return;
}
const hashedPassword = await hashPassword(password);
await db.collection('users').insertOne({
email: email,
password: hashedPassword,
});
res.status(201).json({ message: 'Created user' });
client.close();
}
}

const existingUser = db.collection('users').findOne({ email: email });的值是多少?可能得到一个空对象,而不是预期的NULL。

之类的
if (existingUser && Object.keys(existingUser).length()) {

可能就是你要找的。

最新更新