【问题标题】:Querying with mongoose: how to parce a Mongo _id?使用 mongoose 查询:如何解析 Mongo _id?
【发布时间】:2021-01-20 22:54:36
【问题描述】:

我发现了这个与我类似的问题,但没有解释 Mongoose find query vs $match,我正在尝试做类似的事情。

我设法按今天的日期正确过滤,但我还不能按客户 ID 过滤。

这行得通:

 var today = new Date(dateTime);    
    
    var dd = String(today.getDate()).padStart(2, '0');
                var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 1!
                var mmd = String(today.getMonth()).padStart(2, '0'); //January is 0!
                var yyyy = today.getFullYear();
    
        const filter = {
                    $match: {
                        $and: [
                            { date: { $gt: new Date(Date.UTC(yyyy, mmd, dd)) } },
                            // { client: '5f78a00e97f9aa002aa7ec1c' },
                            { status: 1 }
                        ]
                    }
                };
        
// the correct date is whit mmd not mm
                const dateSent = new Date(Date.UTC(yyyy, mmd, dd));
                console.log(dateSent);
        
                const wpreservationDbagregate = await WorkplaceReservation.aggregate([filter]);
       
                
                res.json(wpreservationDbagregate);

我收到此回复,旧文档已被正确过滤:

[
    {
        "_id": "5f7b93e89d1cb4600e8ce740",
        "status": 1,
        "workplace": 5,
        "date": "2020-10-09T00:00:00.000Z",
        "creator": "5f7b36b090b6e518210c6070",
        "client": "5f78a00e97f9aa002aa7ec1c",
        "userId": "5f7b36b090b6e518210c6070",
        "dateCreated": "2020-10-05T21:45:12.229Z",
        "__v": 0
    },
    {
        "_id": "5f7b95699d1cb4600e8ce742",
        "status": 1,
        "workplace": 2,
        "date": "2020-10-07T00:00:00.000Z",
        "creator": "5f7b36b090b6e518210c6070",
        "client": "5f78a00e97f9aa002aa7ec1c",
        "userId": "5f7b36b090b6e518210c6070",
        "dateCreated": "2020-10-05T21:51:37.219Z",
        "__v": 0
    }
]

但是当通过客户端 ID 进行过滤时它不起作用,即使使用字符串(它在过滤器常量中被注释掉)

我想我必须以某种方式解析它,但我可以找到方法......

这是架构:

import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const workplaceReservationSchema = new Schema({
    client: { type: Schema.Types.ObjectId, ref: 'user', required: [true, 'El espacio de trabajo debe ser reservado para algun Cliente'] },
    workplace: { type: Number, required: [true, 'El espacio de trabajo es un campo obligatorio'] },
    userId: { type: Schema.Types.ObjectId, ref: 'user', required: [true, 'El espacio de trabajo debe ser reservado para algun usuario'] },
    creator: { type: Schema.Types.ObjectId, ref: 'user', required: [true, 'Loging incorrecto'] },
    date: { type: Date, required: [true, 'La reserva debe tener una fecha'] },
    dateModified: { type: Date },
    dateCreated: { type: Date, default: Date.now },
    status: { type: Number, default: 1 }
});

//Set unique compound indexes
workplaceReservationSchema.index({ workplace: 1, client: 1, date: 1, status: 1 }, { unique: true });
workplaceReservationSchema.index({ userId: 1, client: 1, date: 1, status: 1 }, { unique: true });


const WorkplaceReservation = mongoose.model('workplaceReservation', workplaceReservationSchema);

export default WorkplaceReservation;

package.json:

"dependencies": {
        "@babel/cli": "^7.10.4",
        "@babel/core": "^7.10.4",
        "@babel/node": "^7.10.4",
        "@babel/preset-env": "^7.10.4",
        "bcrypt": "^4.0.1",
        "connect-history-api-fallback": "^1.6.0",
        "cors": "^2.8.5",
        "dotenv": "^8.2.0",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.10.7",
        "mongoose-unique-validator": "^2.0.3",
        "morgan": "^1.10.0",
        "underscore": "^1.10.2"
    }

非常感谢!

【问题讨论】:

    标签: json mongodb mongoose match aggregate


    【解决方案1】:

    您是否尝试过将 _id 从字符串转换为 ObjectId ? 类似{ client: mongoose.Types.ObjectId('5f78a00e97f9aa002aa7ec1c') }

    【讨论】:

      【解决方案2】:

      您通常希望将对象 ID 的架构中的变量保留为隐式(未声明,让 Mongo 处理它)

      对于您的用户 ID 和创建者变量,请使用 type: String

      // Schema
      const workplaceReservationSchema = new Schema({
          workplace: { type: Number, required: [true, 'El espacio de trabajo es un campo obligatorio'] },
          userId: { type: String, ref: 'user', required: [true, 'El espacio de trabajo debe ser reservado para algun usuario'] },
          creator: { type: String, ref: 'user', required: [true, 'Loging incorrecto'] },
          date: { type: Date, required: [true, 'La reserva debe tener una fecha'] },
          dateModified: { type: Date },
          dateCreated: { type: Date, default: Date.now },
          status: { type: Number, default: 1 }
      });
      

      那么您的查询可以这样构造:

      const filter = {
          $match: {
              $and: [
                  { date: { $gt: new Date(Date.UTC(yyyy, mmd, dd)) } },
                  { _id: '5f78a00e97f9aa002aa7ec1c' },
                  { status: 1 }
              ]
          }
      };
      

      【讨论】:

      • 非常感谢您的回复,我会尝试使用类型字符串并检查此解决方案!
      • 斯蒂芬,出于某种原因(我是使用猫鼬的新手),当我将 Schema.Types.ObjectId 中的 userID 和 creator 变量更改为使用 type: String 时,它们是唯一复合索引的一部分,不创建。我在过滤器中使用了带有 mongoose.Types.ObjectId('5f78a00e97f9aa002aa7ec1c') 的 Georgios 解决方案,它有效,但我真的很想像你建议的那样简化查询。
      【解决方案3】:

      我终于完成了这个查询。主要思想是按日期分组(这就是我没有使用 find 的原因)

      这是最终代码:

       // Actual GTM -3 DATETIME (Argentina)
              const dateTime = new Date(new Date() - 3600 * 1000 * 3).toISOString();
              var today = new Date(dateTime);
              var dd = String(today.getDate()).padStart(2, '0');
              var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 1!
              var mmd = String(today.getMonth()).padStart(2, '0'); //January is 0!
              var yyyy = today.getFullYear();
              // Actual GTM -3 Date
              today = yyyy + '-' + mm + '-' + dd;
      
              const filter = {
                  $match: {
                      $and: [
                          { date: { $gt: new Date(Date.UTC(yyyy, mmd, dd)) } },
                          { client: mongoose.Types.ObjectId(client) },
                          { status: 1 }
                      ]
                  }
              };
      
              const group = {
                  $group: {
                      _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
                      count: { $sum: 1 }
                  }
              };
              const wpreservationDbfiltered = await WorkplaceReservation.aggregate([filter]);
              const wpreservationDbgrouped = await WorkplaceReservation.aggregate([filter, group]);
      
              res.status(200).json({ wpreservationDbgrouped, wpreservationDbfiltered });
      

      我得到了按日期分组的数据以及这样的所有文档:

      {
          "wpreservationDbgrouped": [
              {
                  "_id": "2020-10-09",
                  "count": 1
              },
              {
                  "_id": "2020-10-07",
                  "count": 1
              },
              {
                  "_id": "2020-10-08",
                  "count": 1
              }
          ],
          "wpreservationDbfiltered": [
              {
                  "_id": "5f7c87d4670b421d387d2614",
                  "status": 1,
                  "workplace": 2,
                  "date": "2020-10-07T00:00:00.000Z",
                  "creator": "5f790ad4cb0b41834f94e91b",
                  "client": "5f78dac286bfd05f21527e49",
                  "userId": "5f790ad4cb0b41834f94e91b",
                  "dateCreated": "2020-10-06T15:05:56.258Z",
                  "__v": 0
              },
              {
                  "_id": "5f7c929ed1901826d50af73d",
                  "status": 1,
                  "workplace": 3,
                  "date": "2020-10-08T00:00:00.000Z",
                  "creator": "5f790ad4cb0b41834f94e91b",
                  "client": "5f78dac286bfd05f21527e49",
                  "userId": "5f790ad4cb0b41834f94e91b",
                  "dateCreated": "2020-10-06T15:51:58.621Z",
                  "__v": 0
              },
              {
                  "_id": "5f7c92a5d1901826d50af73e",
                  "status": 1,
                  "workplace": 6,
                  "date": "2020-10-09T00:00:00.000Z",
                  "creator": "5f790ad4cb0b41834f94e91b",
                  "client": "5f78dac286bfd05f21527e49",
                  "userId": "5f790ad4cb0b41834f94e91b",
                  "dateCreated": "2020-10-06T15:52:05.373Z",
                  "__v": 0
              }
          ]
      }
      

      非常感谢您的帮助!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-19
        • 1970-01-01
        • 2014-10-08
        • 2016-09-17
        • 2021-07-14
        • 2014-12-30
        • 2017-08-15
        相关资源
        最近更新 更多