Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating Mongoose objects from id to new field

I was working with mongoose to populate field of ids with their respective documents to a new field.my question is assuming my cart model is -

let CartSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    productIds: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        }
    ]
});

i want to populate the products so i used

Cart.find({}).populate("products").exec(function (err, cart) {
    console.log(cart)
}

but this populates the documents in the same field name productIds and i want to populate those fields in a new field name called "products" so i tried this

let CartSchema = new mongoose.Schema({
        userId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        },
        productIds: [
            {
                type: String
            }
        ]
    }, { toJSON: { virtuals: true } });

CartSchema.virtual('products', {
    ref: 'Product',
    localField: 'productIds',
    foreignField: '_id',
});

Cart.find({}).populate("products").exec(function (err, cart) {
    console.log(cart)
}

but returned empty array named products.so how can i populate the productIds array to a new field name products with their respective document array.

Thanks.

like image 281
Natnael Getachew Avatar asked Jan 29 '19 20:01

Natnael Getachew


People also ask

How does populate work in Mongoose?

Mongoose Populate() Method In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

What is the __ V field in Mongoose?

In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.

Can we overwrite Mongoose default ID with own id?

You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.


2 Answers

There's a way to do this - it's called Virtuals (see docs). The idea is to create a "virtual property" which is not actually saved to the DB and acts as a computed property. As per the example provided by qinshenxue on the related github issue:

// declare your ID field as a regular string
var countrySchema = new mongoose.Schema({
    capitalId: {type:String}
});

// create a virtual field which links between the field you've just declared 
// and the related collection. 
// localField is the name of the connecting field, 
// foreign field is a corresponding field in the connected collection
// justOne says that it'll populate a single connected object, 
// set it to false if you need to get an array
countrySchema.virtual('capital',{
    ref: 'City',
    localField: 'capitalId',
    foreignField: '_id',
    justOne: true
});

// tell Mongoose to retreive the virtual fields
countrySchema.set('toObject', { virtuals: true });
countrySchema.set('toJSON', { virtuals: true });

// now you can populate your virtual field like it actually exists
// the following will return a Country object in the 'capital' field
Country.find().populate('capital') 
like image 53
grreeenn Avatar answered Oct 11 '22 23:10

grreeenn


the approch is correct you should see your data poulated in the products field. make sure you have the correct data and model n

like image 40
yehualashet Abebe Avatar answered Oct 11 '22 22:10

yehualashet Abebe