【发布时间】:2020-09-01 02:40:22
【问题描述】:
我试图检索与 id 关联的数据,并将其存储在变量中。 我的数据库看起来像
{
"_id" : ObjectId("5ebc4242c2098c7968853b44"), //userId
"firstname" : "john",
"lastname" : "Jacob",
"username" : "john@abc.com",
"comments" : [
{
"_id" : ObjectId("5ebd124e7f92505c9c23b680"),
"comment" : "hey there",
"imagename" : "image-1589449294815.PNG"
},
{
"_id" : ObjectId("5ebd24b9cae2ab15683460ed"),
"comment" : "whazup",
"imagename" : "image-1589454009062.jpeg"
}
我正在检索特定的 id(通过复选框选择的图像),并且想要访问特定的评论和关联的图像名称(通过 id),然后通过将图像发送到我的 .ejs 文件SIMG
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);
【问题讨论】:
-
贴出Schema的代码
-
hii,我已经编辑了上面的代码以添加架构。谢谢
-
所以你需要得到只匹配checkedItemId的评论,这个checkedItemId应该代表comment._id还是什么?
-
什么是_id类型?
-
是的,我需要同时获取与checkedItemId相关的评论和图片名称。当我登录checkedItemId时,我得到了id值(例如上面senerio中的“5ebd124e7f92505c9c23b680”,我可以通过checkedItemid登录,但我想要评论,即“嘿那里”及其相关的图像名称,即“image-1589449294815.PNG” " ) @mohammedyousry
标签: node.js mongodb mongoose ejs