Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'TypeError: meme.find(...).forEach is not a function' in mongoose node js?

I want to loop through my collection in MongoDB so I tried .forEach to perform the action but it looks like this is not the right approach. Everytime I tried running it gives me error: TypeError: meme.find(...).forEach is not a function

This is my code:

var meme = require('../app/model/meme');

meme.find().forEach(function(meme){
   meme.update({_id: meme._id}, {$set: { objectID: meme._id.toString().slice(10).slice(0,24)}}); 
});

I'm using mongoose and node.js to perform the action.

I'd appreciate any help to solve this problem.

Thanks.

like image 370
Counter J Avatar asked Sep 07 '25 16:09

Counter J


1 Answers

You're using an async method find so you should use promises or callback to get the result , here some solutions choose what you want

// using promises

meme.find().then((memes) => {
  memes.forEach((meme) => {
    console.log(meme);
  });
});

// using callbacks

meme.find({}, (err, memes) => {
  memes.forEach((meme) => {
    console.log(meme);
  });
});

// using exec

meme.find().exec((err, memes) => {
  memes.forEach((meme) => {
    console.log(meme);
  });
});
like image 65
mostafa tourad Avatar answered Sep 10 '25 02:09

mostafa tourad