如何使用 Mongoose 和 nanoid 修复我的 URL 缩短重定向逻辑?

问题描述 投票:0回答:1
// models/urlModel.js
import mongoose, { Schema } from "mongoose";
import { nanoid } from "nanoid";

const Urlschema = new Schema({
    originalUrl: {
        type: String,
        required: true,
    },
    shortCode: {
        type: String,
        required: true,
        unique: true,
        default: () => nanoid(6),
    },
    clicks: {
        type: Number,
        default: 0,
    },
}, {
    timestamps: true,
});

const Url = mongoose.model("Url", Urlschema);
export default Url;
    
// How can I fix my URL shortening redirection logic using Mongoose and nanoid?
// Redirect to the original URL based on shortCode

    export const redirectToOriginalUrl = async (req, res) => {
        const { shortCode } = req.params; // Extract shortCode from the URL params
    
        try {
            // Find the URL document based on the shortCode
            const urlDoc = await Url.findOne({ shortCode });
    
            // If the URL document is not found, return a 404 error
            if (!urlDoc) {
                return res.status(404).send('Short URL not found');
            }
    
            // Increment the click count for this URL
            urlDoc.clicks += 1;
            await urlDoc.save(); // Save the updated document
    
            // Redirect to the original URL
            return res.redirect(urlDoc.originalUrl);
        } catch (error) {
            console.error('Error in redirecting to original URL:', error); // Log the error for debugging
            return res.status(500).send('Server Error'); // Send a generic server error response
        }
    };

我尝试访问 localhost:5001/shortCode,并收到错误消息: "message": "检索链接时出错", “错误”:“对于模型“Url”的路径“_id”处的值“va1QMm”(类型字符串),转换为 ObjectId 失败”

如何解决?

mongoose schema nanoid
1个回答
0
投票

使用调试器来识别代码损坏的位置,但是根据您的错误消息,我可以说您的 mongodb 中会出现错误,您能否告诉我有关错误的更多信息并查看您正在使用哪种请求方法。

© www.soinside.com 2019 - 2024. All rights reserved.