【问题标题】:Query an array after populating with mongoose.js使用 mongoose.js 填充后查询数组
【发布时间】:2016-03-03 14:59:42
【问题描述】:

我正在尝试在填充相应对象后查询引用数组。我有一种感觉,我要么没有使用正确的操作 $...,要么我的方法不是解决我需要做的事情的正确方法。

我将举一个例子来明确我想要做什么。假设我有一组用户,他们可以有多个与之关联的预订文档。我需要找到所有居住在某个位置并且至少有一个开始日期在今天之前的预订的所有用户。

模型大致如下:

var Booking = new mongoose.Schema({
    starts_at: { type: Date },
    ends_at:   { type: Date },
    //...
});

var User = new mongoose.Schema({
    name: String,
    location: String,
    bookings: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Booking' }],
    //...
});

我正在尝试的代码/查询如下:

User.find({ 'location': 'some place' })
    .populate('bookings')
    .where({ 'bookings.starts_at': { $lte: new Date() } })
    .exec(function(err, users) {
        //...
    });

任何帮助或见解都会很棒

【问题讨论】:

  • 非常相似,但是那里的方法会给我一个匹配的预订数组,因为我需要用户作为结果来使用
  • 此外,Bookings 不包含反向引用 - 该引用是对(用户)执行初始/首次查询的同一模型的一部分,因此该方法很遗憾不起作用:(

标签: node.js mongodb mongoose


【解决方案1】:
 User
     .find({ 'location': 'some place'})
     .populate('bookings', null, 'starts_at' : { $lte: new Date()})
     .exec(function(err, result) {
        if (!err) {

            console.log(result);
        } else {
           console.log(err)
        }
 });

请试试这个!!

【讨论】:

  • 谢谢,在最后一个 arg 周围添加缺少的括号后,这可以正常工作
  • @Scott 这不会排除在今天之前没有至少一个预订的用户。
  • 谢谢@JohnnyHK,是的,我用users = users.filter(function(user){ return user.bookings.length; }) 过滤掉了那些——除非你能建议我可以在数据库查询中包含的方法?
猜你喜欢
  • 2014-11-03
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 2018-07-31
  • 2017-01-20
相关资源
最近更新 更多