murvinlai
murvinlai

Reputation: 50345

How come Mongoose return empty document when find by id of an array?

The schema is like that:

var feedSchema = new mongoose.Schema({
  id: {type: Number},
  following: []
});

and my code using promise is very simple:

  var Feed = require("/models/feed");

  return Feed.find({"following" : id}).exec();

I have data like this:

{
 id:1, following: [2,3,4]
}

but when I set the id for query, it doesn't return anything. Any idea?

Upvotes: 0

Views: 545

Answers (1)

Wilson
Wilson

Reputation: 9136

It should be working, I am providing an example which works ok, probably you can contrast your logic with this one and know which part could be the problem.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost:27017/murvinlai');

var FeedSchema = new Schema({
  id: Number,
  following: [Number]
});

var Feed = mongoose.model('Feed', FeedSchema);

var newFeed = {
  id: 1,
  following: [2, 3, 4]
};

createFeed(newFeed, function(err, feed) {
  if (err) throw err;

  findFeedByFollowingArray(2).then(function(feeds) {
    console.log(feeds); 
    //  [ { _id: 55a486a11ef682b41e13e82a,
    //      id: 1,
    //      __v: 0,
    //     following: [ 2, 3, 4 ] } ]      
  });
});

function createFeed(feed, cb) {
  Feed.create(feed, function(err, feed) {
    if (err) { return cb(err); }
    if (!feed) { return cb(new Error('Feed was not created')); }

    cb(null, feed);
  });
}

function findFeedByFollowingArray(id) {
  return Feed
    .find({following: id})
    .exec();
}

Upvotes: 1

Related Questions