使用Mongoose在参考文本字段中搜索

时间:2017-04-08 22:46:07

标签: node.js mongodb

我有这个架构

var users = new Schema({
    name: {type: String, required: true},
    email: {type: String, required: true},
    password: {type: String, required: true},
    following: [{type: Schema.ObjectId, ref: "users"}]
});
users.index({name: 'text'});

我想使用Mongoose查找名称中包含“john”的用户,并且他们存在于以下_id = x

的用户数组中

以其他方式,如果它是SQL,则查询将是(它只是用于说明关系的示例)

SELECT * FROM users where _id = x AND users.following.name LIKE '%john%'

我认为如果将以下数组嵌入到用户集合中,则很容易实现。

我如何处理猫鼬?

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案http://mongoosejs.com/docs/populate.html 我将填充匹配

一起使用
.findById("x", {following: 1}).populate({ path: 'following',match: {$text: {$search: "john"}}})