find not working on mongoose document

304 views Asked by At

My model looks like this

/* models/songs.js */
var mongoose = require('mongoose');

var SongsSchema = new mongoose.Schema({
    genres: [ String ],
    popularity: Number,
    trackId: String,
    artistIds: [ String ],
    users: [ String ],
    trackName: String // human readability
});

var Songs = mongoose.model("Songs", SongsSchema);

module.exports = {
  Songs: Songs
};

This is what is in my routes

/* routes/index.js */
var mongoose = require('mongoose');
var Songs = mongoose.model('Songs');

router.get('/api/genre', function(req, res, next) {
  var genre = req.query.genre.replace(/%26/, '&');
  genre = req.query.genre.replace(/-/g, ' ');

  console.log('attempting to find', genre);
  Songs.find({
    genres: genre
  }, function(err, songs, count) {
    console.log('count', count);
    console.log('songs', songs);

    res.json(songs.map(function(song) {
      console.log('hello ', song);
      return song.trackId;
    }));
  });
});

"attemping to find" logs out perfectly fine, but none of the lines in the Songs.find callback is logging out anything. The weird part about this is that it's not giving me any error. Another weird thing is that I also tried used the Songs.find in other parts of routes/index.js and they work fine. I've also tried using findOne and other functions on my Songs document, but they don't seem to be working. I've also tried looking at other StackOverflow questions, but none of them seem to have my answer.

2

There are 2 answers

0
abhi On

try this

Songs.find({
  genres: genre
}).exec(function(err, songs) {
    console.log('songs', songs);
    res.json(songs.map(function(song) {
      console.log('hello ', song);
      return song.trackId;
    }));
});
0
Ravi Shankar Bharti On

The callback in find Query takes 2 arguments, the first one is the error and the second one is the array of mathced documents.

In your query, you have provided 3 arguments. change it to 2 and see if that works.I guess, it will work without any problem.

For count you can do songs.length

Do this:

Songs.find({
    genres: genre
  }, function(err, songs) {
    console.log('count', songs.length);
    console.log('songs', songs);

    res.json(songs.map(function(song) {
      console.log('hello ', song);
      return song.trackId;
    }));
  });