【问题标题】:find array in document and filter by years and month在文档中查找数组并按年和月过滤
【发布时间】:2016-11-14 17:35:46
【问题描述】:

我使用 nodejs 和猫鼬。我有这样的架构:

var comptesSchema = new Schema ({
name: String,
solde: Number,
user_id: Number,
operations: [{
    name: String,
    amount: Number,
    debit: Boolean,
    mensuel: Boolean,
    date: Date,
    category: String
}]

});

还有我的数据:

[{
"_id": "5826d10b829c732cacd92f6f",
"name": "compte courant",
"__v": 0,
"solde": -40,
"operations": [
  {
    "date": "2016-11-12T23:00:00.000Z",
    "debit": false,
    "amount": 10,
    "name": "tivoli",
    "_id": "5828b1bf42ae876e287525dc"
  },
  {
    "date": "2016-11-12T23:00:00.000Z",
    "debit": false,
    "amount": 20,
    "name": "st georges",
    "_id": "5828d1e1c951b07888e79c61"
  },
  {
    "date": "2016-11-11T23:00:00.000Z",
    "debit": false,
    "amount": 10,
    "name": "oiufdsouifd",
    "_id": "5828d51e679a4a7718a55b48"
  }
]}]

我想在操作数组中查找元素,并按年和月过滤。

你有什么想法吗?谢谢:)

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    假设您为monthyear 设置过滤选项如下:

    var month = 11;
    var year = 2016;
    

    试试这个:

    comptesSchema.find({'operations.date': {
        "$gte": new Date(year, month, 1),
        "$lt": new Date(year, month, 0)
      }, function (err, comptes) {
        // Get you filtered comptes
    });
    

    【讨论】:

      【解决方案2】:

      我有两个手术:一个在 11 月,一个在 12 月。

      我试试这个:

          .get('/compte/:compteId/operation/date', function(req, res) {
          var compteId = req.params.compteId;
          var month = 11;
          var year = 2016;
          Comptes.find({
              'operations.date': {
                  "$gte": new Date(year, month, 1),
                  "$lt": new Date(year, month, 0)
              }
          }, function(err, compte) {
              res.json(compte);
          });
      })
      

      但它不起作用,我有这个:

      [{
      "_id": "5826d10b829c732cacd92f6f",
      "name": "compte courant",
      "__v": 0,
      "solde": -70,
      "operations": [
        {
          "date": "2016-11-13T23:00:00.000Z",
          "debit": false,
          "amount": 10,
          "name": "test",
          "_id": "58297e475c208d081c810aec"
        },
        {
          "date": "2016-12-13T23:00:00.000Z",
          "debit": false,
          "amount": 20,
          "name": "fsdf",
          "_id": "58297e655c208d081c810aed"
        }
      ]}]
      

      它返回的日期是 11 月和 12 月.. 我不明白 :(

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-12
        • 2021-03-23
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        相关资源
        最近更新 更多