将数据从词汇传递到EJS

发布于 2025-01-29 16:26:46 字数 723 浏览 2 评论 0原文

我有以下型号

const userSchema = new mongoose.Schema({
    username: String,
    likes: Number
})

和一条路线,

app.get("/users/:id", async(req, res) => {
    const id = req.params.id
    let cc = await User.find({ username: id });
    let raw = cc;
    res.render('index', {data : raw})

})

当我碰到这条路线时,它可以正常工作,并且在前端,它打印了由CC返回的数组。即

[{"_id":"6282d457f697743c1145a02","username":"John","likes":0,"__v":0}]

,但是,在html方面,如果我尝试访问<%= data [0] .likes%>,我会

同样获得“喜欢”的不确定错误,当我尝试通过一个对象对EJS的特定属性,例如,

res.render('index', {data : raw[0].likes}

我遇到一个错误,说 无法读取未定义的属性(读取“喜欢”)

为什么发生此错误

I have the following model

const userSchema = new mongoose.Schema({
    username: String,
    likes: Number
})

and a route

app.get("/users/:id", async(req, res) => {
    const id = req.params.id
    let cc = await User.find({ username: id });
    let raw = cc;
    res.render('index', {data : raw})

})

when I hit this route it works fine and on the front end, it prints the array that is returned by cc. i.e

[{"_id":"6282d457f697743c1145a02","username":"John","likes":0,"__v":0}]

But, on the HTML side, if I try to access <%= data[0].likes %> I get an undefined error for "likes"

Similarly, when I try to pass a specific property of the object to ejs for example

res.render('index', {data : raw[0].likes}

I get an error that says
Cannot read properties of undefined (reading 'likes')

why is this error occurring

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文