[英]Search inside a Mongoose model with node.js and express.js
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. 但是我不知道谁在用户内部搜索在following和followers数组内部搜索。 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
. 很容易,我能做到这一点UserModel.find({ user: req.session.user }, function(err, user){[...]})
但是这里面,我要搜索的阵列内部的特定字符串following
和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. 我可以使用for loop
来做到这一点,但是我想如果数组中有很多String,搜索一个字符串将会很慢,甚至是有问题的。 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
. 我认为这段代码行不通,但是也许有一种无需使用for loop
即可执行我想要的方法的方法。 Any solution...? 任何解决方案...?
No, you can't call findOne
on the user
document instance. 不,您不能在user
文档实例上调用findOne
。 What you can do instead is include the following
field in your main UserModel.findOne
call like this: 相反,您可以做的是在主UserModel.findOne
调用中包括following
字段:
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
. 在回调中, user
只可以设置当用户在跟踪randomstring
。
Of course, you can also use array.indexOf
to easily search the array in code: 当然,您也可以使用array.indexOf
轻松在代码中搜索数组:
if (user.following.indexOf(randomstring) !== -1) {
// user is following randomstring
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.