1

I actually searched a ton and I saw a ton of mentions of my problem here but none of the things I tried helped me fix the issue i'm having.

I have a Room Scheme that looks like this:

const ObjectId = mongoose.Schema.ObjectId;
const roomSchema = mongoose.Schema({
users: [{
    type: ObjectId,
    ref: 'User'
}],
messages: [{
    type: ObjectId,
    ref: 'Message',
}],
post: {
    type: ObjectId,
    ref: 'Post'
  }
});

As you can see I have an array of users with ref to another schema Users

I'm trying to query all the Rooms that has a User ObjectId in it (search ObjectId in an array).

while I can easily get this with querying mongo from cmd using this:

db.users.find({users:ObjectId('THE_OBJECT_ID')});

when I try to get the same while using mongoose it fails with:

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

Here is how my route and find looks like:

  app.route('/rooms/list/:user_id')
    .get((req, res) => {
        var query = { users: "USER_ID" };
        Room.find(query ).populate('messages').then((data) => {
            res.status(200).json(data);
        }).catch((err) => {
            console.log(err);
        });
     })

I tried to create type of object ID and use it but it still doesn't work.

var mongoose = require('mongoose'),
userId = 'THE_USER_ID';
var id = mongoose.Types.ObjectId(userId);

and than

Rooms.find({'users': id });

but it still doesn't work.

I also tried altering my query search using $in, $elemmatch it worked on cmd but failed when querying using mongoose.

Any help would be appreciated.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
Yoni hodeffi
  • 103
  • 2
  • 8
  • Your input should be `user_id`, convert it to `ObjectId()` and then query. So value of `user_id` should be a string that obeys `ObjectId()`'s restrictions, You can take string from existing doc's `ObjectId()` & test your `get` api.. – whoami - fakeFaceTrueSoul May 20 '20 at 01:49

1 Answers1

0

Issue :

If you check this :

var query = { users: "USER_ID" };

(Or)

userId = 'THE_USER_ID';
var id = mongoose.Types.ObjectId(userId);

What are you trying to do here ? You are passing in string USER_ID or THE_USER_ID as input and trying to convert it to type of ObjectId(). But string inside ObjectId() has certain restrictions which is why mongoose is failing to convert passed in string value to ObjectId() and getting error'd out.

Try this code :

Code :

const mongoose = require('mongoose');


app.route('/rooms/list/:user_id')
    .get((req, res) => {
        var query = { users: mongoose.Types.ObjectId(req.params.user_id) };
        Room.find(query).populate('messages').then((data) => {
            res.status(200).json(data);
        }).catch((err) => {
            console.log(err);
        });
    })

Your input should be value of user_id (Which will be string) - Convert it to ObjectId() and then query DB. So value of user_id should be a string that obeys ObjectId()'s restrictions, You can take string from one of existing doc's ObjectId() & test your get api.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • Server fails on: var query = { users: mongoose.Types.ObjectId(req.params.user_id) }; Error: No default engine was specified and no extension was provided. – Yoni hodeffi May 20 '20 at 06:49
  • @Yonihodeffi : try to debug with logs, this error shouldn’t be from that part of code..Check this : https://stackoverflow.com/questions/23595282/error-no-default-engine-was-specified-and-no-extension-was-provided – whoami - fakeFaceTrueSoul May 20 '20 at 06:50
  • I was able to fix the err, though query still returns empty result which is weird since querying directly to mongo yields stuff – Yoni hodeffi May 20 '20 at 18:17
  • @Yonihodeffi : Since you're able to fix this error this question is resolved, You can close this. To test why you're getting this error - print `req.params.user_id` and check if you'r getting a value that exists in atleast one docs `_id` field, Also check if conversion of string to `ObjectId()` is properly working.. – whoami - fakeFaceTrueSoul May 20 '20 at 18:26