【发布时间】:2020-12-16 08:51:50
【问题描述】:
在我之前的 html 代码中,当我提交它时,它会向 /comment/:id 发送一个帖子,然后网站崩溃并输出 MongoError: Unsupported projection option: $push: { comment: {内容:“gfdghd”} } 在我的控制台中。我不知道如何解决它,我希望我能在这个问题上得到一些帮助,因为我是 web 开发的初学者。
我希望通过将包含 req.body 的数组推送到某个 mongodb 数组默认集合中,它可以在其中找到父帖子 _id。如果需要我详细说明,请询问,谢谢。
这是我的代码:
app.js
const Post = require("./models/Post");
mongoose
.connect("secret", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: true,
})
.then(() => {
console.log("connected to mongodb cloud! :)");
})
.catch((err) => {
console.log(err);
});
app
.post("/comment/:id", authenticateUser, async (req, res) => {
const content = req.body;
// checks for missing fields
if (!content){
return res.send("Please enter all the required credentials!");
}
//This is where I tried to match and then push it to mongodb
Post.update({"_id": ObjectId(req.params.id) }, {
$push: {
comment: content,
}
}, function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
})
发布猫鼬模式
Post.js
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
postedAt: {
type: String,
default: new Date().toString()
},
postedBy: {
type: String,
},
warned: {
type: String,
},
comment: [String]
});
module.exports = new mongoose.model("Post", PostSchema);
除数组功能外,其他一切都有效。
【问题讨论】: