我在 Node.js 中重定向 url 时遇到奇怪的错误

问题描述 投票:0回答:1

我正在尝试使用 Node.js 创建一个 URL 缩短器。 我已经设置了一个生成随机 ID 的 POST 请求
此请求采用重定向 URL。 在创建使用短 ID 重定向到原始 URL 的 GET 请求时,我遇到了一个奇怪的错误。 每当我更改从 URL 中提取短 ID 的变量名称 (req.params.shortId) 并确保相应地更新 findOneAndUpdate() 方法中的搜索字符串时,我都会得到一个 null 条目(结果模型)。

20: app.get("/:shortId", async(req, res) => {
21:    const shortId = req.params.shortId;
22:    const entry = await URL.findOneAndUpdate(
23:      {
24:        shortId  // if changed here and in line 20: 'const shortId'
25:                // to any other name entry becomes null why?
26:      },
27:    res.redirect(entry.redirectURL); //redirecting to the original URL
28:  });
node.js express mongoose-schema
1个回答
0
投票

您似乎对语法感到困惑

findOneAndUpdate({ shortId })

这实际上是

findOneAndUpdate({ shortId: shortId })
的缩写,正在查找字段
shortId
是指定变量值的数据库条目。

如果您将缩写形式的变量名称(“自动属性”,如果您需要谷歌搜索)更改为

myShortId
,则您正在查找数据库条目,其中字段
myShortId
是指定的变量值。

如果您使用长符号,则可以重命名变量:

const myShortId = req.params.shortId;
const entry = await URL.findOneAndUpdate({shortId: myShortId});

注意对象键仍然是

shortId
,因此会搜索到正确的DB字段。

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