mongoose findOne()不再接受回调如何修复此错误

vc6uscn9  于 2023-04-30  发布在  Go
关注(0)|答案(1)|浏览(151)

此代码不起作用,它给出错误“模型。findOne()不再接受回调”。修复错误而不降级我的 Mongoose 版本。
`router.post('/ login',async(req,res)=〉{

const email = req.body.email;
const password = req.body.password;
const userType = req.body.userType;

let userSchema;
let redirectUrl;

// Set the user schema and redirect URL based on the user type
if (userType === 'customer') {
    userSchema = Customers;
    redirectUrl = '/customer/home';
} else if (userType === 'hotel_owner') {
    userSchema = HotelOwners;
    redirectUrl = '/hotel_owner/home';
} else if (userType === 'advertiser') {
    userSchema = Advertisers;
    redirectUrl = '/advertiser/home';
} else if (userType === 'destination_manager') {
    userSchema = DestinationManagers;
    redirectUrl = '/destination_manager/home';
} else if (userType === 'admin') {
    userSchema = Admin;
    redirectUrl = '/admin/home';
}

// Find the user in the corresponding schema
await userSchema.find({ email: email, password: password })
    .then(user => {
        if (!user) {
            // If user not found, return error message
            res.status(401).send({
                message: "Invalid email or password"
            });
        } else {
            // Redirect user to their respective home page
            res.redirect(redirectUrl);
        }
    })
    .catch(err => {
        // Handle errors
        console.error(err);
        res.status(500).send({
            message: "An error occurred"
        });
    });

});`
如何修复错误并运行此代码

tquggr8v

tquggr8v1#

既然你已经在使用await了,就像这样做吧:

try {
    const user = await userSchema.findOne({email, password})
    if (!user) {
        //If there is no user match, do...
    }
    // If there is a user, do something below...
} catch (error) {
    // Handle error here
}

另外,我相信您必须使用模型而不是模式来调用像find()这样的函数

const User = mongoose.model("User", userSchema)
const users = User.find() // Or similar functions

相关问题