Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose saving with objectId

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.

like image 856
sawa Avatar asked Oct 04 '15 14:10

sawa


People also ask

How do I get the ObjectId after I save an object in mongoose?

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.

What is ObjectId in 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.

Is Mongoose ObjectId unique?

yes, the unique: true index guarantees it "in this one collection" - the algorithm "almost" guarantees it universally.

Does Mongoose auto generate ID?

_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.


1 Answers

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.

like image 169
Gaurav Gandhi Avatar answered Oct 22 '22 23:10

Gaurav Gandhi