Populate a property of a mongoose schema with all the data in another collection

Hi everyone

I have a model with articles, and would like to populate an array of data with all the documents in a collection.

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ArticlesSchema = new mongoose.Schema({
  path: {
    type: String,
    required: true,
    unique: true,
  },
  base_headline: {
    type: String,
    required: true,
  },
  intro: {
    type: String,
    required: true,
  },
  featured_image: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  platform_filter: {
    type: String,
  },
  free_filter: {
    type: String,
  },
  content_type: {
    type: String,
    required: true,
  },
  data: [{ type: Schema.Types.ObjectId, ref: 'DesignProducts' }],
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model('Articles', ArticlesSchema);

The data property should be populated with all documents in the DesignProducts collection.

I tried running this but the data array is still empty:

Article.findOne({ path: slug }).populate('data').exec();

Here is what the designProducts model looks like:

const mongoose = require('mongoose');

const DesignProductsSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
  },
  intro: {
    type: String,
    required: true,
  },
  website: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model('DesignProducts', DesignProductsSchema);

This array should be populated with all the documents in the DesignProducts collection:

Skjermbilde 2021-01-19 132341

1 Like

I wanted to the same thing, but I was unable to find any documentation only so I used a pymongo script

    # Get my array
    data = my_coll.find({})

    all_data = []

    for document in data :
        all_data .append({str(document["_id"]):"myproperty"})
    
    # add array if does not exist
    some_other_collection.update_many({},
    {
        "$addToSet":
        {
            "my_array": all_data 
        }
    })