0

I have a MongoDB model like:

Posts: id, category, data[title, description, slug..]  

I was adding my data to my_array but now I need to add category field

my_array = []

my_array[:posts] = Posts.all.to_a.map { |p| p.data }

How can I merge them to see this result?

my_array: {[ category1, title1, description1, slug1], [ category2, title2, description2, slug2]}

So, I want to push the category field into the same array, but I don't know how to change this query

 my_array[:posts] = Posts.all.to_a.map { |p| p.data }
3
  • can you please explain what do you want to merge? do you want to merge the multiple arrays into one big array with all the fields? Commented Apr 10, 2021 at 10:49
  • no, I want to add the category field to my_array. But category and data array should be same level.. Commented Apr 10, 2021 at 10:52
  • I can do my_array[:posts] = Posts.all.to_a.map { |p| p } and get all posts , but if i do so, data and category won't be in same level.. Commented Apr 10, 2021 at 10:53

1 Answer 1

1

if you want to merge the category to the hash you will need to get the data then merge a category key with the category

my_array[:posts] = Posts.all.to_a.map { |p| p.data.merge(category: p.category) }
Sign up to request clarification or add additional context in comments.

8 Comments

I've tried it but could not get the category field..
can you post what you actually got out of one record and post the record's columns as well?
Actually i get it into array but its like: [{'title' => 'a' , 'descrition'=> 'a'}, BSON::ObjectId('60715018bee8403af3a10d11') ]
if you check my answer, category_id is a bson object. But it's not on same level with other data. It's not in same curly brackets..
are you able to call .str on the BSON::ObjectId('60715018bee8403af3a10d11') and get the value back?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.