0

I have two Mongoose Schemas:

var ItemSchema = new Schema({  
    trade: {
        type: Schema.Types.ObjectId,
        ref: 'Trade'
    }
});

var Item = mongoose.model('Item', ItemSchema);

and

var TradeSchema = new Schema({
    expiresOn: {
        type: Date
    }
});

var Trade = mongoose.model('Trade', TradeSchema);

I am trying to use Item.find() to find a item if its trade date is less than the date the user passes in via the query string in the request. I'm using the following code:

if (req.query.expiresBefore) {
    Item.find({
        'trade.expiresOn': {
            $lte: req.query.expiresBefore
        }
    }, function (err, trades) {
        console.log(trades)
    })
}

However, I am receiving an empty array on the console.log() call. Using $gte also returns an empty array (though my research tells me that I need to use $lte for my purposes). What do I need to do to find the item document by matching the property (expiresOn) of its child (Trade)?

1 Answers1

0

Referring to this one Stackoverflow question, what you want to do is not possible.I am not sure why you set the schemas like this, but if you want to keep them as they are. I would suggest you make a little change like the following

var ItemSchema = new Schema({  
    trade: {
        type: Schema.Types.ObjectId,
        ref: 'Trade'
    }
});

var Item = mongoose.model('Item', ItemSchema);

and

var TradeSchema = new Schema({
    itemId: { //add this
        type: Schema.Types.ObjectId,
        ref: 'Item'
    },
    expiresOn: {
        type: Date
    }
});

var Trade = mongoose.model('Trade', TradeSchema);

if (req.query.expiresBefore) {
    Trade.
        find({
            'expiresOn': {
                $lte: req.query.expiresBefore
            }
        }).
        populate('itemId').
        exec(function (err, trades) {
            console.log(trades)
        });
}
Community
  • 1
  • 1
David
  • 241
  • 2
  • 11