타임스탬프에 가장 적합한 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는Date
type(기본적으로 타임스탬프):
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()
});
번째 : 첫째번 :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
'programing' 카테고리의 다른 글
org.json을 복제하려면 어떻게 해야 하나요?Java의 JSONObject? (0) | 2023.02.28 |
---|---|
ES6/ES7 구문을 사용하여 jQuery UI를 가져오려면 어떻게 해야 합니까? (0) | 2023.02.28 |
인증 유형 10이 지원되지 않아 Postgres DB에 연결할 수 없습니다. (0) | 2023.02.28 |
하이버네이트를 사용한 Spring Boot에서의 데이터베이스 이행 처리 방법 (0) | 2023.02.28 |
BEGIN - PL/SQL에서 Atomic 트랜잭션을 종료합니다. (0) | 2023.02.28 |