Ad

Mongoose (array In Array) - How To Insert?

- 1 answer

enter image description here

Hello, I would like to insert data into "rss" array. How can I do this? That's how I add new categories into users collection:

  user.findOneAndUpdate({
    _id: req.body.ownerId
  },
  { $push: {
    categories: {
      name: req.body.categoryName,
      public: false
    }
  }},
  { safe: true, upsert: true },
  function(err, model) {
    console.log(err);
  });

But how can I add something into Sport/rss? Firstly I need to find an user by id and secondly I need to find a category also by id. How to do that and finally insert into?

my variables: req.body.ownerId - user id req.body.categoryId - category id req.body.url - rss url which I want to insert into categories array

Thanks for you help.

Ad

Answer

It is not recommended that you maintain an array within an array. It is often better to maintain a separate collection for the categories.

That said, you'll need to execute two queries: one to populate the categories array for the user and the other to populate the rss array in the categories array for the same user.

In the first update query:

// Populate the 'categories' array. Insert the empty 'rss' array.
...
{ $push: 
  categories: {
    name: req.body.categoryName,
    public: false,
    rss: []
  }
}
...

In the second update query:

// Populate the 'rss' array for the same user.
...
{ $push:
  'categories.$.rss': req.body.url
}
...

The second update query will be executed in the callback of the first one.

Ad
source: stackoverflow.com
Ad