Search code examples
javascriptmongodbmongoosesubdocument

Mongoose: How to add additional field into subdocument array


I have a question regarding mongoDB, namely mongoose:

Let's say I have 2 models: 1) Product model 2) User model

const ProductSchema = new Schema({
  title: String,
  description: String,
  product_type: String,
  image_tag: String,
  created_at: Number,
  price: Number
});
const Product = module.exports = mongoose.model('product', ProductSchema);

const UserSchema = new Schema({
  login: String,
  email: String,
  password: String,
  purchases: [{
    type: Schema.Types.ObjectId,
    ref: 'product'
  }]
});
const User = module.exports = mongoose.model('user', UserSchema);

When the user buys some goods, I just add product to purchases array in user model(using push method). If I need to match purchase's ID to its full description I use populate.

The problem is I need somehow to control quantity of each purchase made by user -> I need additional field in each purchase object inside array...something like quantity or total, like that:

const UserSchema = new Schema({
     ...
      purchases: [{
        type: Schema.Types.ObjectId,
        ref: 'product',
        quantity: {
          type: Number,
          default: 1
        }
      }]
    });

I'm stuck and have no clue how to implement this. Example above does not work.


Solution

  • Try this, this way will definitely work:

    const UserSchema = new Schema({
        purchases: [{
                ref: {
                     type: Schema.Types.ObjectId,
                     ref: 'product'
                },
                quantity: {
                  type: Number,
                  default: 1
                }
              }]
     });