我将注释发布到/ arms /:id / comments,如下所示,但总是收到错误,无法读取push undefined的属性
router.post("/", middleware.isLoggedIn, function(req, res) {
arms.findById(req.params.id, function(err, armsFound) {
if (err) {
console.log(err);
res.redirect("back");
} else {
comments.create(req.body.comment, function(err, comment) {
if (err) {
console.log(err);
res.redirect("back");
} else {
comment.author.id = req.user._id;
comment.author.username = req.user.username;
comment.save();
arms.comments.push(comment);
arms.save();
req.flash("success", "Successfully added comment");
res.redirect("/arms/" + arms._id);
}
});
}
});
});
arm schema在arm Schema注释中是一个数组,在Internet上的每个位置(包括stackoverflow),我都发现,如果我将某些内容推入数组,则可以,否则,它将返回错误。我还阅读了一些关于stackoverflow的内容,建议我使用实际的词(需要注释模式使用该词)来推送,在我的情况下为“ comments”,所以我写了“ comments”,而不是下面的代码中写有“ comment”的代码。但这也没有用
const mongoose = require("mongoose");
const armSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: String,
image: String,
description: String,
owner: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String,
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}]
})
module.exports = mongoose.model("arms", armSchema);
注释架构
const mongoose = require("mongoose");
const commentSchema = new mongoose.Schema({
text: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
})
module.exports = mongoose.model("Comment", commentSchema);
看起来在您的代码中arms
是模型,而不是文档,因此arms.comments
未定义。将其更改为armsFound
将在您的回调中findById()
解决该问题。像这样:
armsFound.comments.push(comment);
armsFound.save();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句