Home > Software design >  Mongoose schema two fields as one
Mongoose schema two fields as one

Time:12-27

I want to combine and save the shopid and email in new field named as combined. how its schema should be written so it automatically saves in db

  shopId: { type: String, required: true },
  id: { type: String, required: true },
  email: { type: String, required: true },
  firstname: { type: String, required: true },
  lastname: { type: String, required: true },
  _shopId: { type: mongooose.Schema.Types.ObjectId, ref: 'Shop', required: true },

  combined: shopid   email 
  
})

CodePudding user response:

mongodb cannot enforce that combined will always be shopId email; you could always go in after-the-fact and update the combined field to something else. I recommend both saving a bit a space and moving the logic into the agg pipeline, e.g.

db.foo.aggregate([
  {$addFields: {combined: {$concat: [ "$shopId", "$email" ]} }}
]);

or for better clarity perhaps

db.foo.aggregate([
  {$addFields: {combined: {$concat: [ "$shopId", "-", "$email" ]} }}
]);

CodePudding user response:

You can't do it automatically from a schema. If you want that "combined" field, you need to define it as an object or a string (if you're thinking on a string like ${email}${id}):

shopId: { type: String, required: true },
  id: { type: String, required: true },
  email: { type: String, required: true },
  firstname: { type: String, required: true },
  lastname: { type: String, required: true },
  _shopId: { type: mongooose.Schema.Types.ObjectId, ref: 'Shop', required: true },
  // In case you need a separation of your fields
  combined: { 
      email: {
          type: String,
          required: true
      },
      shopId:{
          type: String, 
          required: true 
      }
}
  //In case you need that one combined string
  combined: {
      type String,
      required: true
  }

And then you add your "combined" field in your logic when saving that document.

  • Related