MongoDB Mongoose JS时间序列不工作

vs91vp4v  于 2023-03-23  发布在  Go
关注(0)|答案(1)|浏览(124)

我正在使用NodeJS和Mongoose JS。我试图通过在项目中利用MongoDB时间序列来创建用户分析。我是一个新开发人员。我不知道我在这里做错了什么。数据库没有显示任何更改。
我想把每天的用户分析保存在我的时间序列中。
我的Mongoose架构:

import { Schema, model } from "mongoose";
const User = new Schema(
  {
    email: {
      type: String,
      unique: true,
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
    analytics: {
      type: Array,
      required: true,
      default: [
        {
          date: new Date(),
          country: {},
          browser: {},
          os: {},
        },
      ],
    },
  },
  {
    timestamps: true,
    timeseries: {
      timeField: "createdAt",
      metaField: "email",
      granularity: "seconds",
    },
    expireAfterSeconds: 86400,
  }
);

export default model("User", User);

输出如下所示:

{
  "_id": {
    "$oid": "641b2811c93e3ca1ae196995"
  },
  "email": "email1@email.com",
  "name": "Name Name",
  "analytics": [
    {
      "date": {
        "$date": {
          "$numberLong": "1679501306802"
        }
      }
    }
  ],
  "createdAt": {
    "$date": {
      "$numberLong": "1679501329465"
    }
  },
  "updatedAt": {
    "$date": {
      "$numberLong": "1679501356039"
    }
  },
  "__v": 0
}

谁能告诉我如何正确地实现时间序列?

sczxawaw

sczxawaw1#

我怀疑你正在使用MongoDB 5.0。你需要使用createCollection()创建TS集合,同时在你的模式中禁用 autoIndex

const userSchema = new mongoose.Schema(
    {
        email: {
            type: String,
            unique: true,
            required: true,
        },
        name: {
            type: String,
            required: true,
        },
        analytics: {
            type: Array,
            required: true,
            default: [
                {
                    date: new Date(),
                    country: {},
                    browser: {},
                    os: {},
                },
            ],
        },

    },
    {
        timestamps: true,
        autoIndex: false,
    },
);

const UserModel = mongoose.model("User", userSchema);

async function run() {

    await dropCollections();
    await UserModel.createCollection({
        timeseries: {
            timeField: "createdAt",
            metaField: "email",
            granularity: "seconds",
        },
        expireAfterSeconds: 86400,
    })
};

mongoose.connect(url)
    .then(async () => run())
    .catch(console.dir)
    .finally(() => {
        mongoose.disconnect();
    });

希望能有所帮助!
最好的,

相关问题