2

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.

2
  • Cast your participants id with ObjectId... Conversation.find({ participants: ObjectId("5b758a8341ee61f049ded486") }) Commented Sep 14, 2018 at 16:05
  • Tried this mongoose.Types.ObjectId("5b758a8341ee61f049ded486") but still same empty array response. Commented Sep 14, 2018 at 16:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.