1

Mongo is driving me crazy. I have these schemas:

var userSchema = new Schema({
username: {
    type: String,
    require: true,
    unique: true
},
password: {
    type: String,
    require: true,
}
});
var User = mongoose.model('user', userSchema);

var deviceSchema = new Schema({
name: {
    type: String,
    require: true,
    unique: true
},
type: String,
lastvalue: {
    type: Schema.ObjectId,
    ref: 'event'
},
owner: {
    type: Schema.ObjectId,
    ref: 'user',
    require: true
},
apiKey: {
    type: String,
    unique: true,
    default: function() {
        return crypto.randomBytes(64).toString('hex');
    }
}
});
var Device = mongoose.model('device', deviceSchema);

and I want to retrieve all devices of a user. So: Device.find({'owner.username': req.params.username})

But it returns an empty array! I've also tried: Device.find({'owner.username': req.params.username}, {'owner':1}) Device.find({'owner.username': req.params.username}, {'owner.$':1) Without any luck... I've searched the whole internet but I can't find anything useful!

dzervas
  • 250
  • 2
  • 14

1 Answers1

0

You need to get the associated user _id first then query the Device model on the owner field using the _id from the first user query. The following shows this approach:

User.findOne({ "username" : req.params.username }),
    .exec(function(err, user) {
        if (err) throw err;
        Device
        .find({"owner": user._id})
        .populate('owner', 'username') // only return the username
        .exec(function(err, devices) {
            if (err) throw err;
            console.log(JSON.stringify(devices, undefined, 4));
        });
    }
);
chridam
  • 100,957
  • 23
  • 236
  • 235