In mongoose I've got this model:
var userschema = new mongoose.Schema({
user: String,
following: [String],
followers: [String]
});
var UserModel = db.model('UserModel', userschema);
But I don't know who search, inside a user, search inside the following and followers array. Easily, I can do this UserModel.find({ user: req.session.user }, function(err, user){[...]})
But inside that, I want to search a specific string inside the arrays following and followers. I can do it using a for loop, but I think if I have a lot of String inside the array, search one would be slow, or even problematic. Is posible do this?:
UserModel.findOne({ user: req.session.user }, function(err, user){
if (err) throw err;
user.findOne({ following: randomstring }, function(err, nuser){
if (err) throw err;
});
});
I think that this code won't work, but maybe there is a way to do what I want without using a for loop. Any solution...?
No, you can't call findOne on the user document instance. What you can do instead is include the following field in your main UserModel.findOne call like this:
UserModel.findOne({ user: req.session.user, following: randomstring },
function(err, user){ ...
In the callback, user would only be set if that user was following randomstring.
Of course, you can also use array.indexOf to easily search the array in code:
if (user.following.indexOf(randomstring) !== -1) {
// user is following randomstring
}