How can I generate an ObjectId with mongoose ?

How can I generate an ObjectId with mongoose ?

Asked on January 8, 2019 in MongoDB.
Add Comment


  • 2 Answer(s)

    We can find the ObjectId constructor on require(‘mongoose’).Types. For the  example below:

    var mongoose = require('mongoose');
    var id = mongoose.Types.ObjectId();
    

    id is a freshly generated ObjectId.

    To refer more about the types object at Mongoose#Types documentation.

     

     

    Answered on January 8, 2019.
    Add Comment

    You can using mongoose to create a new MongoDB Objectid.

    var mongoose = require('mongoose');
    var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
    // or leave the id string blank to generate an id with a new hex identifier
    var newId2 = new mongoose.mongo.ObjectId();
    

     

    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.