Mon*_*okh 12 javascript mongoose mongodb node.js
在使用mongoose填充之后,通过匹配文档内部的值来查询文档时遇到了一些麻烦.
我的架构是这样的:
var EmailSchema = new mongoose.Schema({
type: String
});
var UserSchema = new mongoose.Schema({
name: String,
email: [{type:Schema.Types.ObjectId, ref:'Email'}]
});
Run Code Online (Sandbox Code Playgroud)
我希望所有用户都拥有类型为"Gmail"的电子邮件.
以下查询返回空结果:
Users.find({'email.type':'Gmail').populate('email').exec( function(err, users)
{
res.json(users);
});
Run Code Online (Sandbox Code Playgroud)
我不得不求助于在JS中过滤结果,如下所示:
users = users.filter(function(user)
{
for (var index = 0; index < user.email.length; index++) {
var email = user.email[index];
if(email.type === "Gmail")
{
return true;
}
}
return false;
});
Run Code Online (Sandbox Code Playgroud)
有没有办法从mongoose直接查询这样的东西?
bar*_*sny 17
@Jason Cust已经很好地解释了 - 在这种情况下,最好的解决方案通常是改变模式以防止查询Users存储在单独集合中的文档的属性.
这是我能想到的最好的解决方案,不会强迫你这样做(因为你在评论中说过你不能).
Users.find().populate({
path: 'email',
match: {
type: 'Gmail'
}
}).exec(function(err, users) {
users = users.filter(function(user) {
return user.email; // return only users with email matching 'type: "Gmail"' query
});
});
Run Code Online (Sandbox Code Playgroud)
我们在这里做的只是填充email匹配的附加查询(调用中的match选项.populate()) - 否则文档中的email字段Users将被设置为null.
剩下的就是.filter返回的users数组,就像你原来的问题一样 - 只有更简单,非常通用的检查.正如你所看到的 - 无论email是存在还是不存在.
Mongoose的populate功能不能直接在Mongo中执行。相反,在初始find查询返回一个文档集之后,populate将find在引用的集合上创建单个查询的数组以执行,然后将结果合并回到原始文档中。因此,实质上,您的find查询尝试使用被引用文档的属性(尚未获取,因此是undefined)来过滤原始结果集。
在这种用例中,将电子邮件存储为子文档数组而不是单独的集合以实现您想要的工作似乎更为合适。另外,作为一般的文档存储设计模式,这是将数组存储为子文档的用例之一:有限的大小和很少的修改。
将架构更新为:
var EmailSchema = new mongoose.Schema({
type: String
});
var UserSchema = new mongoose.Schema({
name: String,
email: [EmailSchema]
});
Run Code Online (Sandbox Code Playgroud)
然后,以下查询应该工作:
Users.find({'email.type':'Gmail').exec(function(err, users) {
res.json(users);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20662 次 |
| 最近记录: |