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 havescreensfiltered to the first element that matches your query selector.Like this: