Search code examples
node.jsmongodbmongooseconcatenation

How to concatenate string with another key value in the same Mongoose Schema


Is it possible to concatenate a string and a value of a previous key value in the same Mongoose schema? The below responds with account is not defined

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let TrackingSchema = new Schema({
    account: { type: String, required: true, max: 100 },
    accountURL: "https://www.instagram.com/" + account,
    followedBack: { type: Number, required: true }
},
{
    timestamps: true
});

// Export the model
module.exports = mongoose.model("Tracking", TrackingSchema);

Solution

  • You can create a virtual property:

    TrackingSchema.virtual('accountURL').get(function(){
        return "https://www.instagram.com/" + this.account;
    });