I'm trying to use the mongoose find method to find an object on an unknown object. Here is the code to explain better.
Here are my models :
var Screen = new mongoose.Schema({
id : Number,
pid : Number,
uploaded : {type: Date, default: Date.now },
name : String,
url : String,
shorty : String
});
var User = new mongoose.Schema({
id : Number,
mail: { type : String, match : /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/ },
pass: String,
token: String,
inscDate: { type: Date, default: Date.now },
lastConnec: { type: Date, default: Date.now },
screens: [Screen],
lastIp : String,
valid : { type: Boolean, default : 0}
});
var UserModel = mongoose.model('users', User);
var ScreenModel = mongoose.model('screens', Screen);
So the thing is that my user model contains an array of screens. Basically I want to search a precise screen for an unknown user. Doing something like this :
var query = UserModel.find({'screens.shorty' : shorty});
query.exec(function(err, screenR) {
});
But this code crashes, and the other similar codes I tried never returns anything else than an empty array. And my search isn't wrong (I tried to copypasta an exact string).
Is there any working way to do that ?
If you're using MongoDB 2.2+ you can use the $
projection operator to have screens
filtered to the first element that matches your query selector.
Like this:
var query = UserModel.findOne({'screens.shorty': shorty}, {'screens.$': 1});
query.exec(function(err, user) {
if (user) {
// user.screens[0] contains the first element with the matching shorty field
}
});
Okay, I managed to make this work. Not sure this is the most elegant way, but at least it is a way :
var query = UserModel.find({'screens.shorty' : shorty}); // That query will get me the correct user, but not the screen
query.exec(function(err, screenR) {
if (err) throw err;
if (screenR[0]){
for (var i in screenR[0].screens){ // I loop through all the screens
if (screenR[0].screens[i].shorty == shorty) {
// Here I have the correct screen and can do whatever with it.
}
}
} else {
// If no result
}
});