首先,我想为我的英语不好而道歉。
我是Web开发主题的超级新手。目前,我正在为一个问题而苦苦挣扎。我的研究未成功,所以我希望你们中的任何人都能提供帮助。
我的问题是我无法将子文档“ post”写入我的文档“ user”中并将其保存到mongodb中。
我已经阅读了很多有关stackoverflow,mongodb,mongoose等的文档,但是我找不到适合我的解决方案。
´´´´´´
//Schema for Posts
const postSchema = new mongoose.Schema({
postAuthor: String,
postTitle: String,
postContent: String,
});
//Schema for Users
const userSchema = new mongoose.Schema({
username: String,
password: String,
posts: [postSchema]
});
//Create Collection
const User = mongoose.model("User", userSchema);
//Create Collection
const Post = mongoose.model("Post", postSchema);
´´´´´´´
//None working part of my code
//Save new Post as subdoc post to doc user
app.post("/compose", function(req, res) {
User.find({
_id: req.user._id
}, function(err, user) {
console.log("User found: " + user);
const post = new Post({
postAuthor: req.user._id,
postTitle: req.body.postTitle,
postContent: req.body.postContent
});
console.log("New Post: " + post);
//TypeError: Cannot read property 'push' of undefined
user.posts.push(post);
user.save();
console.log("Saved");
});
});