i试图检索与id关联的数据,并将其存储在变量中。我的数据库看起来像
{
"_id" : ObjectId("5ebc4242c2098c7968853b44"), //userId
"firstname" : "john",
"lastname" : "Jacob",
"username" : "[email protected]",
"comments" : [
{
"_id" : ObjectId("5ebd124e7f92505c9c23b680"),
"comment" : "hey there",
"imagename" : "image-1589449294815.PNG"
},
{
"_id" : ObjectId("5ebd24b9cae2ab15683460ed"),
"comment" : "whazup",
"imagename" : "image-1589454009062.jpeg"
}
i正在检索(通过复选框选择的图像的)特定ID,并想访问特定注释和关联的图像名称(通过ID),然后通过SIMG将图像发送到我的.ejs文件中] >
app.js看起来像
app.post("/checkout", uploads, function (req, res) { User.findById(req.user.id, function (err, foundUser) { if (err) { console.log(err); } else { if (foundUser) { const uid = foundUser.id; //this is users id. var checkedItemId = req.body.checkbox; // this is checked image id. User.findById(checkedItemId, function (err, foundID) { if (foundID) { console.log(foundID); console.log(foundID.comment); console.log(foundID.imagename); res.render("checkout", { SIMG: imagename, }); } }); if (Array.isArray(req.body.checkbox)) { res.render("checkout", { SIMG: req.body.checkbox, }); } else { res.render("checkout", { SIMG: [req.body.checkbox], }); } } } }); });
我正在使用上述findById方法,但似乎无法正常工作,或者我可能未使用正确的方法。
模式看起来像
const commentSchema = new mongoose.Schema({
comment: String,
imagename: String,
});
const Comment = new mongoose.model("Comment", commentSchema);
const userSchema = new mongoose.Schema({
firstname: String,
lastname: String,
email: String,
password: String,
comments: [commentSchema],
});
const User = new mongoose.model("User", userSchema);
i试图检索与id关联的数据,并将其存储在变量中。我的数据库看起来像{“ _id”:ObjectId(“ 5ebc4242c2098c7968853b44”),// userId“ firstname”:“ john”,“ lastname”:“ ...
[findById
方法用于通过文档的_id
获取文档,因此,当您将checkedItemId
传递给User.findById(checkedItemId)
时,它将不返回任何内容,因为此checkedItemId
不是userId
,它是commentId