Saving Mongoose with objectId

I am trying to save comments for a post. When I send a comment from the client side, the comment should be saved with the ObjectId of the message that I collect from the mail page - req.body.objectId. I tried the method below, but that only gives me a 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 functions? Thank you in advance.

+4
source share
1 answer

Wrong way to insert referenced typed values.

You need to do it,

router.post('/api/comment', function(req, res, next){
    var comment = new Comment({
        postId: db.Types.ObjectId(req.body.objectId),
        contents: 'contents'
    }

It will work according to your desire.

+4
source

Source: https://habr.com/ru/post/1610181/


All Articles