我创建了一个URL缩短器.我使用POST方法创建了一个短ID,并将其插入到数据库中,模式如下:ShortenID,url,visitedAt. POST One成功,数据库也在更新. 但此redirectToUrl方法返回的url未找到.我控制台记录了ShortenID,它正确地记录在日志(log)中. 奇怪的是,我得到了这个日志(log),该日志(log)末尾的Clog(ShortenID)为空.
我也在遵循MVC模式.我还在学习 node ,以防这个信息会有什么不同
{
_id: new ObjectId('657eaf900cd00ca7d2bc1f4d'),
shortenID: '6j9qxUFy58',
url: 'www.google.com',
visitedAt: [
{
timestamps: 1702801419523,
_id: new ObjectId('657eb00b0cd00ca7d2bc1f4f')
},
{
timestamps: 1702801436348,
_id: new ObjectId('657eb01c50c29d064a9b0736')
},
{
timestamps: 1702801815416,
_id: new ObjectId('657eb1979745efd6c70277fb')
},
{
timestamps: 1702802115286,
_id: new ObjectId('657eb2c3e77a78206b63dd26')
},
{
timestamps: 1702802206807,
_id: new ObjectId('657eb31ee1dd0e92e114fb37')
},
{
timestamps: 1702802335263,
_id: new ObjectId('657eb39fed9735b46e0cc78e')
},
{
timestamps: 1702802591675,
_id: new ObjectId('657eb49f0f02975f1ce96300')
},
{
timestamps: 1702802694745,
_id: new ObjectId('657eb506e3930f6479e4aa59')
},
{
timestamps: 1702802791317,
_id: new ObjectId('657eb5670ab01847226c6d9a')
},
{
timestamps: 1702803258471,
_id: new ObjectId('657eb73a52dbb7a72d182143')
}
],
createdAt: 2023-12-17T08:21:36.795Z,
updatedAt: 2023-12-17T08:54:18.473Z,
__v: 0
}
null
async function redirectToUrl(req, res) {
const shortenID = req.params.id
const urlBody = await URL.findOneAndUpdate({
shortenID
},
{
$push: {
visitedAt: {
timestamps: Date.now(),
}
}
})
// console.log(urlBody);
if (urlBody) {
// Redirect to the URL if the document exists
return res.redirect(urlBody.url);
} else {
// Handle the case where no document was found
return res.status(404).send('URL not found');
}
}