【发布时间】:2023-03-26 22:59:01
【问题描述】:
我有app.get 路由来显示包含_id、名称、描述的项目文档。这是我目前拥有的:
app.get('/itemEdit/:itemID', isLoggedIn, (req, res) => {
//console.log("params", req.params)
const item_id = req.params.itemID
//console.log("ID", item_id)
//Here you could query the db and find the item in the array on the user object
User.find({ _id: req.user._id },
(err, docs) => {
// console.log(docs[0].userInventory)
if (err) { console.log(`error: ${err}`) }
else {
console.log(docs);
//You could render edit item page form then make a post route where you query the db and update the item
res.render('itemEdit.ejs', {item_id, docs})
}
})
console.log("Item query", item_id)
})
我知道这是抓取正确的项目,因为我的 console.log 显示正确的 ID。然后,我尝试显示数据,但这是我碰壁的地方。我有item id,但如何显示同一项目中的名称和描述?我试过了:
<table>
<!-- Table Headers -->
<tr>
<th>#</th>
<th>Item Name</th>
<th>Description</th>
</tr>
<!-- Table Data -->
<tr>
<td><%= userInventory[item_id].name %></td>
<td><%= userInventory[item_id].description %></td>
</tr>
<% } %>
</table>
这给了我一个错误:SyntaxError: Missing catch or finally after try
任何帮助将不胜感激!
编辑:
用户架构:
let userSchema = mongoose.Schema({
username: String,
firstName: String,
lastName: String,
email: String,
password: String,
userInventory: [{
name: String,
description: String
}]
});
【问题讨论】:
-
您的查询有错误
{ _id: req.user._id, _id: item_id },您正尝试通过_id进行查询,但您为_id传递了两个不同的值。此外,res.render('itemEdit.ejs', {item_Id})仅将item_Id发送到您的视图,即req.params.itemID的值。你应该发送docs -
您能否发布您的用户架构,这将有助于回答您的问题
-
感谢您指出该错误!我现在明白你只发送 item_id 的意思了。我现在将尝试使用文档!
-
@knicholas 我添加了 userSchema。
-
@knicholas 我删除了传递给
_id的额外值并将docs传递到渲染中,但我仍然遇到同样的错误。我想我需要改变我在表单中显示数据的方式。
标签: javascript node.js database mongodb ejs