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
findOneon theuserdocument instance. What you can do instead is include thefollowingfield in your mainUserModel.findOnecall like this:In the callback,
userwould only be set if that user was followingrandomstring.Of course, you can also use
array.indexOfto easily search the array in code: