简体   繁体   English

如何在node.js中构造特定查询以从mongodb获取数据?

[英]How can I construct a specific query in node.js to fetch data from mongodb?

I'm using mogoosejs and have a data model: 我正在使用mogoosejs并有一个数据模型:

var UserSchema = new Schema({
    username: {type: String, required: true},
    location: {type: [Number], required: true}, // [Long, Lat]
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

Now on that schema I want to perform a query that will find all the users within certain area, so I did as follows: 现在,在该架构上,我想执行一个查询,该查询将找到特定区域内的所有用户,因此我做了如下操作:

var query = User.find({});
if(distance){
    query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},
    maxDistance: distance * 1609.34, spherical: true});
}

So that works super well, but now I want to add another parameter to this query - date. 这样效果很好,但是现在我想向该查询添加另一个参数-日期。 So I want to find all users within a specific location and that created their accound during last 16 hours... How should I modify my query to get all those results? 因此,我想找到一个特定位置的所有用户,这些用户在过去16个小时内创造了他们的声音。如何修改查询以获取所有这些结果? Thanks a lot for any clues! 非常感谢您提供任何线索!

To add the date query, create a date object that represents the datetime 16 hours ago: 要添加日期查询,请创建一个代表16小时前的datetime的日期对象:

var start = new Date();
start.setHours(start.getHours()-16);

Use the above in your query now as: 现在在查询中将以上内容用作:

// get coordinates [ <longitude> , <latitude> ]
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;
var criteria = { 
        "created_at": { "$gte": start }
        "location": {
            "$near": coords,
            "$maxDistance": distance * 1609.34
        }
    },
    query = User.find(criteria);

If the opportunity shows, use moment.js library, a super handy utility for doing manipulations like this. 如果有机会,请使用moment.js库,这是一个超级方便的实用程序,用于执行此类操作。 To use it for such scenario, you'd call the subtract() method as: 要在这种情况下使用它,您可以按以下方式调用subtract()方法:

var start = moment().subtract(16, 'hours'),
    criteria = { "created_at": { "$gte": start }},
    query = User.find(criteria);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM