Project repo https://github.com/zootechdrum/scrapeWithMongo
Hello again,
I am having trouble storing multiple comments on blog posts in my MongoDB collection. There is no authentication so anyone on the site can feel free to comment whatever they like. What I am trying to do is add comments to one blog post. As of now I have only been successful in updating the one comment associated with the blog post. However, I can’t seem to save multiple comments into one collection.
I am using mongoose.
//comment schema
var mongoose = require("mongoose");
// Save a reference to the Schema constructor
var Schema = mongoose.Schema;
// Using the Schema constructor, create a new CommentSchema object
// This is similar to a Sequelize model
var CommentSchema = new Schema({
// `body` is of type String
body: String
});
// This creates our model from the above schema, using mongoose's model method
var Comment = mongoose.model("comment", CommentSchema);
// Export the Note model
module.exports = Comment;
var mongoose = require("mongoose");
// Save a reference to the Schema constructor
var Schema = mongoose.Schema;
// Using the Schema constructor, create a new UserSchema object
// This is similar to a Sequelize model
var ArticleSchema = new Schema({
image: {
type: String,
required: true
},
// `title` is required and of type String
title: {
type: String,
required: true
},
// `link` is required and of type String
link: {
type: String,
required: true
},
description: {
type: String,
required: true
},
// `comment` is an object that stores a Note id
// The ref property links the ObjectId to the Comment model
// This allows us to populate the Article with an associated Comment
comment: {
type: Schema.Types.ObjectId,
ref: "comment"
}
});
// This creates our model from the above schema, using mongoose's model method
var Article = mongoose.model("Article", ArticleSchema);
// Export the Article model
module.exports = Article;
Below is the route where I would like to save more comments. Its not working though.
app.post("/articles/:id", function(req, res) {
console.log(req.body)
// Create a new note and pass the req.body to the entry
db.Comment.create(req.body)
.then(function(dbComment) {
// console.log(dbComment)
// // If a Note was created successfully, find one Article with an `_id` equal to `req.params.id`. Update the Article to be associated with the new Note
// // { new: true } tells the query that we want it to return the updated User -- it returns the original by default
// // Since our mongoose query returns a promise, we can chain another `.then` which receives the result of the query
return db.Article.update({ _id: req.params.id }, { $push: {comment: dbComment._id }})
})
.then(function(dbArticle) {
// If we were able to successfully update an Article, send it back to the client
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurred, send it to the client
res.json(err);
});
});
}