1
0 Comments

Mongo DB: Update data using `.forEach()`

db.getCollection("posts")
  .find({})
  .forEach((item) => {
    const newValues = item.resources
      ? item.resources.map((label) => ({ label }))
      : [];
    item.resources = newValues;
		
    db.posts.save(item);
  });

Task: Convert an array of string into array of object.
.forEach() can be used for some complex operations/migrations


Before: { _id: jf340f34f..., resources: [‘R1’] }
After: { _id: jf340f34f..., resources: [{label: ‘R1’}] }

Trending on Indie Hackers
How I grew a side project to 100k Unique Visitors in 7 days with 0 audience 49 comments Competing with Product Hunt: a month later 33 comments Why do you hate marketing? 29 comments My Top 20 Free Tools That I Use Everyday as an Indie Hacker 18 comments $15k revenues in <4 months as a solopreneur 14 comments Use Your Product 13 comments