mongoose Schema 为了关联定义时几乎全用的ObjectId, 现在要做模糊搜索了,直接懵了。。大神求解
发布于 7 年前 作者 Studying-Man 3583 次浏览 来自 问答

定义Schema如下: sender : {type: mongoose.Schema.Types.ObjectId, ref: ‘user’}, //发送人id receivers : [{type: mongoose.Schema.Types.ObjectId, ref: ‘user’}], //收件人id copiers : [{type: mongoose.Schema.Types.ObjectId, ref: ‘user’}], //抄送人id 数组 title : {type: String, default: ‘’}, content : {type: String, default: ‘’}, //邮件内容 html字符串 files : [{type: mongoose.Schema.Types.ObjectId, ref: ‘files’, default: ‘’}], //附件url地址 数组 这是个邮件部分的Schema,现在要对其做模糊搜索,发现用了ObjectId 没法搜索,,, 想法大概是这样写搜索的,虽然肯定是错的: await EmailModel.find({ $or: [ {sender.nickname: new RegExp(searchValue)}, {receivers.nickname: new RegExp(searchValue)}, {copiers.nickname: new RegExp(searchValue)}, ] }).populate([ {path: ‘sender’, select: ‘nickname’}, {path: ‘receivers’, select: ‘nickname’}, {path: ‘copiers’, select: ‘nickname’}, {path: ‘files’} ])…execAsync(); 请问下大神们,这种情况该怎么处理?

2 回复

只能查两次,先查符合条件的用户的objectid再用这个列表去筛选邮件

找了文档充裕找到了。。可以在populate里面写 操作符 Story. find(…). populate({ path: ‘fans’, match: { age: { $gte: 21 }}, // Explicitly exclude _id, see http://bit.ly/2aEfTdB select: ‘name -_id’, options: { limit: 5 } }). exec()

回到顶部