【发布时间】:2018-07-05 16:30:20
【问题描述】:
最近,我学习了一门名为Web 开发人员课程 的课程。 其中最终项目基于 Camps。 项目中引用了comment数据库和campground数据库,即cmets的ObjectIds发布在 campground 中的内容存储在 array 中。这就是实际发生的事情。
但在我的情况下,确切的情况发生了变化。当我尝试添加 新评论 时,实际发生的是 total object 存储在 cmets 数组,而不是评论的ObjectId。 我几乎已经通过 Stackoverflow 为我的问题寻求解决方案,但失败了。
我只想将 ObjectId 存储在 cmets 数组 中,而不是存储整个 Object,这给我带来了更新和删除的问题一条评论。当我删除或更新评论时,该操作确实发生在 Comments 数据库中,但不会反映在 Campgrounds 数据库中。请帮我解决这个问题。如果有人参加相同的课程,如果您已经经历过类似的事情,请给我解决方案。 Schema 如下所示
露营地架构:
var mongoose = require("mongoose");
var campgroundSchema = mongoose.Schema({
campGroundName: String,
campGroundImage: String,
description: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
],
addedBy: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model("Campground", campgroundSchema);
评论架构:
var mongoose = require("mongoose");
var commentSchema = mongoose.Schema({
text: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model("Comment", commentSchema);
发表评论请求:
router.post("/", middleware.isLoggedIn, function(req, res) {
Comment.create(req.body.comment, function(err, createdComment) {
if(err) {
console.log(err);
} else {
createdComment.author.id = req.user._id;
createdComment.author.username = req.user.username;
createdComment.save(); Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
foundCampground.comments.push(createdComment);
foundCampground.save();
req.flash("success" , "Comment created successfully");
res.redirect("/index/" + req.params.id);
});
}
});
});
完整的源代码如下,
https://1drv.ms/u/s!AmISAco3PGaPhQl_Riu8nroCom5h
请帮我解决这个问题!
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query mongoose-schema