Home > Software engineering >  How to set a field value with same document id in mongoose
How to set a field value with same document id in mongoose

Time:12-27

I want to create a schema on mongoose where a field value is the same as document id.

Desired output:

{
 "_id": "61c75bf3b151c6c6854c83db",
 "password":"some password",
 "name":"some name",
 "linkId": "61c75bf3b151c6c6854c83db"
}

Here document id and linkId is same. How can I do that when creating a new document? It maybe redundant but is it possible?

CodePudding user response:

You can use pre-hook middleware for the save method, when you insert any document it will clone the _id field in to linkId field,

// SCHEMA
const SchemaObj = new mongoose.Schema(
    // your schema...
);

// PRE MIDDLEWARE
SchemaObj.pre('save', function (next) {
    this.linkId = this._id;
    next();
});
  • Related