I am trying to save comments for a post. When I POST a comment from client side, the comment should be saved with the ObjectId of the post, which I collect from the post page - req.body.objectId. I have tried the method below, but it only gives me VALIDATION ERROR.
MODEL
var Comment = db.model('Comment', {
postId: {type: db.Schema.Types.ObjectId, ref: 'Post'},
contents: {type: String, required: true}
}
POST
router.post('/api/comment', function(req, res, next){
var ObjectId = db.Types.ObjectId;
var comment = new Comment({
postId: new ObjectId(req.body.objectId),
contents: 'contents'
}
How can I achieve this? and Is this the right way to implement such functionality? Thank you in advance.
To get the object ID after an object is saved in Mongoose, we can get the value from the callback that's run after we call save . const { Schema } = require('mongoose') mongoose. connect('mongodb://localhost/lol', (err) => { if (err) { console. log(err) } }); const ChatSchema = new Schema({ name: String }); mongoose.
ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
yes, the unique: true index guarantees it "in this one collection" - the algorithm "almost" guarantees it universally.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
That's not proper way of inserting reference typed values.
You have to do it like,
router.post('/api/comment', function(req, res, next){
var comment = new Comment({
postId: db.Types.ObjectId(req.body.objectId),
contents: 'contents'
}
It will work as you desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With