user10364602
user10364602

Reputation: 25

Mongoose find returns empty array

I have mongoDB document which looks like this:

{
    "_id": {
        "$oid": "5b99247efb6fc01dae438815"
    },
    "participants": [
        "5b758a8341ee61f049ded486",
        "5b94fb4ffb6fc01dae40eae3"
    ]
}

The document Schema in Mongoose is defined as such

var conversationSchema = new mongoose.Schema({
    participants: [{ type: mongoose.Schema.ObjectId, ref: 'User'}],
});

I am fetching the data as such

var ccc = Conversation.find({participants : "5b758a8341ee61f049ded486"});
ccc.exec(function(err, conversations){
   res.status(200).json(conversations);
});

The problem is that I am getting an empty array response [].

I think the problem is with Schema but I can't figure out how can I make this to work.

EDIT, If I change my Schema to the following it will work:

var conversationSchema = new mongoose.Schema({
    participants: [{ type: String}],
});

But I want to work with mongoose.Schema.ObjectId and not Strings as foreign key.

Upvotes: 2

Views: 167

Answers (1)

vitomadio
vitomadio

Reputation: 1140

Try adding Types to this line:

participants: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}]

It wont recognize the items in the array because they are strings you should have instead an object like {"$oid": "585bb0086c57cd2265b1cbd3"} so reinsert the items in you db and try again.

Upvotes: 2

Related Questions