微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Mongoose为同一个集合组合了两个查询

我试图根据下面相同集合中的另一个文档进行查询以查找文档.

一个找到用户,第二个通过使用收到的用户数据找到数据.但我想用一个sql中的join这样的查询来做

这是架构

var ConnectionSchema = new Schema({
socketId: {
    type: String,
    require: true
},
location: {
    type: [Number],
    index: '2dsphere'
},
user: { type: Schema.ObjectId, ref: "User" },
date: {
    type: Date,
    require: true,
    default: new Date()
}

});

//查询

return mongoose.model("Connection").findOne({ user: userId }).populate("user").then(usr => {
    return mongoose.model("Connection").find({
        location: {
            $near: {
                $maxdistance: config.searchdistance,
                $geometry: { type: Number, coordinates: usr.location }
            }
        },
        user: { $ne: userId },
    });
});

有没有办法用一个单一的查询来做到这一点?
谢谢.

解决方法:

是的,你可以这样做

    return mongoose.model("Connection").findOne({ user: userId })
.populate("user" ,
        match : {$and : [{location: {
            $near: {
                $maxdistance: config.searchdistance,
                $geometry: { type: Number, coordinates: usr.location }
            }
          }},
           {user: { $ne: userId }}]})
        .then(usr => {
        // perform your action
    });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐