Home > OS >  Dynamically create a collection field based on the user response with mongoose in mongo dB
Dynamically create a collection field based on the user response with mongoose in mongo dB

Time:10-09

I've a database collection where two types of users are there.

1.Customer: They will have all the basic functionalities.

2.Vendor: They will also have the basic functionalities available in addition they can create, delete, update and get/view the vehicles.

suppose a vendor created a vehicle so a vehicle id will get added to the vendor's collection likewise:

{
  . /*other fields*/
  .
  .
  listings: [
   "uniqueId",
   "uniqueId2"
  ]
}

I did some searching and found out that to add vehicle Id's to listings, the field needs to be created first in mongoose otherwise my data will not get inserted in mongodb through mongoose. This rises a problem where all the users have listings field in them.

So, here's my user model I have created:

const userSchema = new mongoose.Schema({
    user_type: {
        type: String,
        required: [true, "user type is required!"],
        enum: ["customer", "vendor", "Customer", "Vendor"],
        default: "customer"
    },
    listings: {
        type: Array,
    },//TODO: only create the listings array if the user type is vendor
});

So, my question is can I create this listing field only if the user_type is vendor?

CodePudding user response:

As defined, in the mongoose documentation, Arrays have a default value of []. So you'll need to override it. Try this:

const userSchema = new mongoose.Schema({
    user_type: {
        type: String,
        required: [true, "user type is required!"],
        enum: ["customer", "vendor", "Customer", "Vendor"],
        default: "customer"
    },
    listings: {
        type: [String], // can also be ObjectId
        default: undefined
    },
}); 
  • Related