vaibhav gera
vaibhav gera

Reputation: 101

Manage duplicate subdocuments in mongoDB using mongoose

Have 2 models.

  1. User
  2. Plants

End user should be able to add multiple quantities of same plant. My User model is:

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

const userSchema = new Schema({
    email: {
        type: String,
        required: true,
    },
    cart: [{
        type: Schema.Types.ObjectId,
        ref: 'Plants',
    }
    ],
    address: [{
        type: Schema.Types.ObjectId,
        ref: 'Contacts'
    }]
});


module.exports = mongoose.model('Users', userSchema)

My Plants model is

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

const plantSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    imageUrl: {
        type: String,
        required: true,
    },
    description: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true
    },
    category: {
        type: String,
        required: true,
    }
});

module.exports = mongoose.model('Plants', plantSchema)

Want my user to contain multiple duplicate subdocuments for plants.

0:6013ab17e5d05b3457cf983a
1:6017ce139e9f3d6d3a616f2b
2:6017ce139e9f3d6d3a616f2b
3:6017ce139e9f3d6d3a616f2b
4:6017ce139e9f3d6d3a616f2b
5:6017ce139e9f3d6d3a616f2b

How should I manage this

Upvotes: 1

Views: 225

Answers (2)

Ritchid Amoah
Ritchid Amoah

Reputation: 83

Use the populate function of mongoose.Document

const doc = await User.findById(id).populate('cart');

You can choose to populate multiple fields in the document by;

const docs = await User.findById(id).populate('cart').populate('address');

Use this link to read more Mongoose populate document

Upvotes: 1

Ahmed Jafri
Ahmed Jafri

Reputation: 49

Every subdocument has its own _id which is generated automatically when you push a Plants document to User document. Which means, 2 same plants would appear with different _id's when you list the User document. Try using

const result = await User.find({}).populate('cart');

This will populate your cart and show you the Plants which have been pushed as subdocuments to your User document

Upvotes: 0

Related Questions