programing

타임스탬프에 가장 적합한 Mongoose 스키마 타입

lovejava 2023. 2. 28. 23:09

타임스탬프에 가장 적합한 Mongoose 스키마 타입

Mongoose, MongoDB, Node를 사용하고 있습니다.

필드 중 하나가 date\timestamp인 스키마를 정의합니다.

이 필드를 사용하여 최근 5분 동안 갱신된 모든 레코드를 반환하고 싶습니다.

Mongoose에서는 Timestamp() 메서드를 사용할 수 없기 때문에 다음 Javascript 메서드를 사용할 수 밖에 없다는 것을 알고 있습니다.

time : { type: Number, default: (new Date()).getTime() } 

대용량 DB를 쿼리하는 가장 효율적인 방법은 아닐 수 있습니다.이것을 보다 효율적으로 실시하는 방법을 공유해 주셨으면 합니다.

이것을 Mongoose로 구현하여 MongoDB 타임스탬프를 사용할 수 있는 방법이 있습니까?

편집 - 2016년 3월 20일

Mongoose는 이제 컬렉션의 타임스탬프를 지원합니다.

아래 @bobbyz의 답변을 검토해 주십시오.어쩌면 이게 네가 찾고 있는 것일 수도 있어.

원답

Mongoose는Datetype(기본적으로 타임스탬프):

time : { type : Date, default: Date.now }

위의 필드 정의에서는 설정되지 않은 상태로 문서를 저장할 때마다time필드, Mongoose는 현재 시간으로 이 필드를 채울 것입니다.

출처 : http://mongoosejs.com/docs/guide.html

현재 버전의 Mongoose(v4.x)에는 스키마에 대한 내장 옵션으로서 다음과 같은 타임스탬프가 있습니다.

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

이 옵션은 추가한다.createdAt그리고.updatedAt타임스탬프가 지정된 속성Date이 모든 것이 도움이 됩니다.문서를 갱신할 때마다 문서가 갱신됩니다.updatedAt소유물.스키마 타임스탬프 문서.

커스텀 네임으로 하고 싶은 경우createdAt그리고.updatedAt

const mongoose = require('mongoose');  
const { Schema } = mongoose;
    
const schemaOptions = {
  timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
};

const mySchema = new Schema({ name: String }, schemaOptions);
var ItemSchema = new Schema({
    name : { type: String }
});

ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps

문서: https://mongoosejs.com/docs/guide.html#timestamps

이것으로 Mongoose는 스키마 내의 타임스탬프를 지원합니다.

const item = new Schema(
  {
    id: {
      type: String,
      required: true,
    },
  { timestamps: true },
);

이렇게 하면createdAt그리고.updatedAt각 레코드의 필드를 만듭니다.

타임스탬프 인터페이스에 필드가 있습니다.

  interface SchemaTimestampsConfig {
    createdAt?: boolean | string;
    updatedAt?: boolean | string;
    currentTime?: () => (Date | number);
  }

이렇게 하면 원하는 필드를 선택하고 날짜 형식을 덮어쓸 수 있습니다.

new mongoose.Schema({
    description: {
        type: String,
        required: true,
        trim: true
    },
    completed: {
        type: Boolean,
        default: false
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    }
}, {
    timestamps: true
});

이 필드를 사용하여 최근 5분 동안 갱신된 모든 레코드를 반환하고 싶습니다.

즉, 개체를 저장할 때마다 날짜를 "지금"으로 업데이트해야 합니다.Moongoose 생성-수정 플러그인이 유용할 수 있습니다.

timestamps:true를 toDateString과 함께 사용하여 날짜를 만들고 업데이트할 수 있습니다.

    const SampleSchema = new mongoose.Schema({
    accountId: {
        type: String,
        required: true
    }
    }, {
       timestamps: true,
       get: time => time.toDateString()
    });

Mongo DB 샘플 문서

번째 : 첫째번 :npm install mongoose-timestamp

하다:let Timestamps = require('mongoose-timestamp')

하다:let MySchema = new Schema

하다:MySchema.plugin(Timestamps)

다니다:const Collection = mongoose.model('Collection',MySchema)

다음 '어울리다'를 .Collection.createdAt ★★★★★★★★★★★★★★★★★」Collection.updatedAt원하는 곳이면 어디든 갈 수 있어요.

작성일 : Date Of The Week Month Date Year 00:00:00 GMT

시간은 이 형식입니다.

언급URL : https://stackoverflow.com/questions/10006218/which-schematype-in-mongoose-is-best-for-timestamp