$ match猫鼬总计

时间:2019-09-06 21:52:30

标签: http mongoose

我正在使用$ match查找在我的架构中引用的用户ID。当我通过http://localhost:3001/api/orders/5d6f1611d3bcd442bc273211/2018-02-01/2019-09-01时,我得到以下信息:

5d6f1611d3bcd442bc273211
[0] 2018-02-01
[0] 2019-09-01
[0] ReferenceError: $match is not defined

这是我的代码:

getOrderTotal: function (req, res) {
    const userID = req.params.userid;
    const firstDate = req.params.firstdate;
    const secondDate = req.params.seconddate;
    console.log(userID);
    console.log(firstDate);
    console.log(secondDate);
    Order
      .aggregate([{ $match: { 'user': userID } }])
      .find({ "created_at": { "$gte": firstDate, "$lt": secondDate } })
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  }

当我删除包含$ match的行时,我得到了预期的结果。当我把它放在里面时,我得到一个空数组。

3 个答案:

答案 0 :(得分:0)

将userId转换为ObjectID

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(userID);

然后在$ match聚合中使用ID

.aggregate([{ $match: { 'user': mongoose.Types.ObjectId(userID) } }])

答案 1 :(得分:0)

我猜这是您想要实现的目标

  1. 查找具有与用户id匹配的用户的文档
  2. 且日期大于或等于firstDate且小于secondDate

如果您坚持使用聚合管道加$ match运算符,则必须了解以下内容

注意: 返回的文档是纯JavaScript对象,不是猫鼬文档(因为可以返回任何形状的文档)。此处更多信息:https://mongoosejs.com/docs/api/aggregate.html

示例:

getOrderByDate: async (req, res) => {

        // Get the parameter data from req.params
        let { user, firstDate, secondDate } = req.params;

        // Convert the user data type to mongoose ObjectId
        user = mongoose.Types.ObjectId(user);

        // Convert both firstDate and SecondDate to date
        firstDate = new Date(firstDate);
        firstDate.setHours(0, 0, 0, 0);

        secondDate = new Date(secondDate);
        secondDate.setHours(23, 59, 59, 999);

        // See the output in your console if you will...

        console.log({ user, firstDate, secondDate });

        // Using async (you can still use promises if you will)
        try {
            const matchedDocuments = await OrderDocument.aggregate([{ $match: { user: user } }]);

            // Filter returned document
            const result = matchedDocuments.filter((docs) => {
                if (docs.created_at >= firstDate && docs.created_at < secondDate) {
                    return true;
                }
            });
            res.status(200).json({ result });
        } catch (error) {
            res.status(500).json({ error, message: 'Something went wrong' });
        }

    }

答案 2 :(得分:0)

您可以使用 expr 一次使用$find$match

const userID = req.params.userid;
const firstDate = req.params.firstdate;
const secondDate = req.params.seconddate;
console.log(userID);
console.log(firstDate);
console.log(secondDate);
Order.find({
   "$expr": { 
       "$and": [
           { "$eq": ["$user", userID] },
           { "$gte": [{ "$created_at": firstDate  }]},
           { "$lt": [{ "$created_at": secondDate  }]}  
       ]
    }
}).exec((err , found)=>{

});