4

I have 2 models,

var locationSchema = mongoose.Schema({
    name: String,
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }]
});

var userSchema = mongoose.Schema({
    name: String,
    email: String
});

I would like to get all Location that has a specific user. For example, with following data,

Location      Users
    A         [1,2,3]
    B         [1,4,5]
    C         [6]

Say, I want to find all locations that has user #1. I've tried following, didn't work

var locationModel = mongoose.model('Location', locationSchema);

locationModel.find({
    users : { $in: user }
});

locationModel.find({
    'users._id' : user._id
});

locationModel.find({
    'users.$oid' : user._id
});

locationModel.find({
    'users.id' : user._id
});

Any idea?

1 Answer 1

2
locationModel.find({
    users : { $in: [some_user_id] }
});
3
  • Would seem right, but unfortunately this guy is using Mongoose models for this, so it is not embedded. See the first schema definition. The documents are in another collection.
    – Neil Lunn
    Feb 22, 2014 at 1:33
  • @zPhiNGpHoNG This may work with an _id but you might want to look into embedded documents if it is going to suit your use case. If you can do that then querying related information from your User Schema is going to be a lot easier.
    – Neil Lunn
    Feb 22, 2014 at 1:42
  • Thanks, Neil. But if I do embedded document, it'll make duplicated data. I prefer not to.
    – ZoM
    Feb 22, 2014 at 2:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.