programing

mongoose 스키마에 created_at 및 updated_at 필드 추가

showcode 2023. 3. 31. 23:02
반응형

mongoose 스키마에 created_at 및 updated_at 필드 추가

와 created_at를 추가하는 요?updated_at스키마로 합니다. mongoose mongoose를 전달할 가 없습니다.매번 새로 작성할 때마다 필드를 전달할 필요가 없습니다.MyModel()★★★★★★★★★★★★★★★★?

created_at필드는 날짜이며 문서가 작성될 때만 추가됩니다.updated_at는 항상 새로운 됩니다.save()문서에서 호출됩니다.

스키마로 시도했지만 명시적으로 추가하지 않으면 필드가 표시되지 않습니다.

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true },
    created_at    : { type: Date, required: true, default: Date.now }
});

업데이트: (5년 후)

주의: Kappa Architecture(이벤트 소싱 + CQRS)를 사용하기로 결정한 경우에는 날짜를 업데이트할 필요가 없습니다.데이터는 변경할 수 없는 추가 전용 이벤트 로그이므로 이벤트 생성 날짜만 필요합니다.아래에 설명된 람다 아키텍처와 유사합니다.그러면 응용 프로그램 상태는 이벤트 로그(파생 데이터)의 투영입니다.기존 엔티티에 대한 후속 이벤트를 수신하면 해당 이벤트에서 생성된 날짜를 엔티티의 업데이트된 날짜로 사용합니다.이것은 마이크로 서비스 시스템에서 일반적으로 사용되는(일반적으로 오해되는) 관행입니다.

업데이트: (4년 후)

「 」를 사용하고 ObjectId_id

let document = {
  updatedAt: new Date(),
}

를 「」, 「」로부터는, 의 원래의 ._id외부 시스템의 ID를 사용해야 할 경우 로만 네스테로프의 답변을 확인하십시오.

업데이트: (2.5년 후)

이제 mongoose 버전 > = 4.0에서 #s 옵션을 사용할 수 있습니다.

let ItemSchema = new Schema({
  name: { type: String, required: true, trim: true }
},
{
  timestamps: true
});

는 mongoose를 할당합니다.createdAt ★★★★★★★★★★★★★★★★★」updatedAt할당된 유형은 다음과 같습니다.Date.

타임스탬프 파일 이름을 지정할 수도 있습니다.

timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }

주의: 중요한 데이터를 사용하는 대규모 응용 프로그램에서 작업하는 경우 문서 업데이트를 다시 고려해야 합니다.불변의 추가 전용 데이터(lambda 아키텍처)를 사용하는 것이 좋습니다.이것은 삽입만 허용한다는 것을 의미합니다.업데이트 및 삭제는 허용되지 않습니다.레코드를 "삭제"하고 싶은 경우 문서의 새 버전을 쉽게 삽입할 수 있습니다.timestamp/version 을 , 「」를 합니다.deleted로 하다true문서를 갱신하는 경우에도 마찬가지로 적절한 필드를 갱신하고 나머지 필드를 복사하여 새 문서를 작성합니다. 삭제되지 않은 되지 않은 버전)을 가져옵니다.deletedfalse(거짓말)

데이터의 불변성을 통해 데이터를 디버깅할 수 있습니다.모든 문서의 이력을 추적할 수 있습니다.또한 문제가 발생할 경우 문서의 이전 버전으로 롤백할 수 있습니다. ObjectId.getTimestamp()필요한 건 몽구스 의존이 아니라


원래 답변:

필드로 ObjectId ID는 created_at에는 objectIds라는 .getTimestamp().

ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()

그러면 다음 출력이 반환됩니다.

이소다테 ("2012-10-15T21:26:17Z")

자세한 내용은 여기를 클릭해 주세요.Mongo 객체에서 작성한 날짜를 추출하려면 어떻게 해야 합니까?아이디

「 」를 하려면 , 「 」를 추가합니다.updated_at하다

var ArticleSchema = new Schema({
  updated_at: { type: Date }
  // rest of the fields go here
});

ArticleSchema.pre('save', function(next) {
  this.updated_at = Date.now();
  next();
});

Mongoose 4.0 이후로는 Schema에서 타임스탬프 옵션을 설정하여 Mongoose가 대신 처리하도록 할 수 있습니다.

var thingSchema = new Schema({..}, { timestamps: true });

다음과 같이 사용되는 필드의 이름을 변경할 수 있습니다.

var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });

http://mongoosejs.com/docs/guide.html#timestamps

결국 이렇게 된 거야

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true }
  , created_at    : { type: Date }
  , updated_at    : { type: Date }
});


ItemSchema.pre('save', function(next){
  now = new Date();
  this.updated_at = now;
  if ( !this.created_at ) {
    this.created_at = now;
  }
  next();
});

된 " " " 를 사용합니다.timestamps옵션을 선택합니다.

var ItemSchema = new Schema({
    name: { type: String, required: true, trim: true }
},
{
    timestamps: true
});

으로 추가가 됩니다.createdAt ★★★★★★★★★★★★★★★★★」updatedAt이치노

http://mongoosejs.com/docs/guide.html#timestamps

timestampsyour Schema 이렇게createdAt ★★★★★★★★★★★★★★★★★」updatedAt됩니다.

var UserSchema = new Schema({
    email: String,
    views: { type: Number, default: 0 },
    status: Boolean
}, { timestamps: {} });

여기에 이미지 설명 입력
바꿀 도 있어요.createdAt -> created_at에 의해

timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }

「」를 사용하고 update() ★★★★★★★★★★★★★★★★★」findOneAndUpdate()

{upsert: true} 표시

하면 .$setOnInsert

var update = {
  updatedAt: new Date(),
  $setOnInsert: {
    createdAt: new Date()
  }
};

Mongoose를 사용하는 NestJ의 경우 다음을 사용하십시오.

@Schema({timestamps: true})

고객님의 고객명model:

const User = Schema(
  {
    firstName: { type: String, required: true },
    lastName: { type: String, required: true },
    password: { type: String, required: true }
  },
  {
    timestamps: true
  }
);

그리고 그 후 당신의modelcollection예요: 이런 거예요.

{
    "_id" : ObjectId("5fca632621100c230ce1fb4b"),
    "firstName" : "first",
    "lastName" : "last",
    "password" : "$2a$15$Btns/B28lYIlSIcgEKl9eOjxOnRjJdTaU6U2vP8jrn3DOAyvT.6xm",
    "createdAt" : ISODate("2020-12-04T16:26:14.585Z"),
    "updatedAt" : ISODate("2020-12-04T16:26:14.585Z"),
}

이것이 제가 만들고 업데이트한 방법입니다.

스키마 내부에 다음과 같이 생성 및 업데이트를 추가했습니다.

/*** 기사 스키마*/var ArticleSchema = 새 스키마({)작성: {            입력: 날짜,            디폴트: Date.now        },
        갱신일 : {            입력: 날짜,            디폴트: Date.now        },제목: {입력:문자열,디폴트: ' ,트림: 참,필수: '제목은 비워 둘 수 없습니다.'},내용: {입력:문자열,디폴트: ' ,트림: 참},사용자: {입력:스키마오브젝트 ID,참조: '사용자'}});

그런 다음 기사 컨트롤러 내의 기사 업데이트 방법에서 다음과 같이 추가했습니다.

/*** 기사 갱신*/exports.update = 함수(요구, res) {var article = req.article;
= _.body(article, req.body);
article.set("updated", Date.now());

article.save(function(err)) {(에러) {res.status(400).send를 반환합니다.메시지: errorHandler.getErrorMessage(err)});} 기타 {res.json(기사);
}});};

굵은 글씨로 표시된 부분이 관심의 대상입니다.

하면 됩니다.timestampstrue다음과 같이 처리한다:-

var ItemSchema = new Schema({
   name :  { type: String, required: true, trim: true },
},{timestamps : true}
);
var ItemSchema = new Schema({
    name : { type: String, required: true, trim: true }
});

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

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

의 플러그인을 사용할 수 있습니다.mongoose-troop이 동작을 임의의 스키마에 추가합니다.

플러그인은 매우 쉽게 사용할 수 있습니다.문서에서:

var timestamps = require('mongoose-timestamp');
var UserSchema = new Schema({
    username: String
});
UserSchema.plugin(timestamps);
mongoose.model('User', UserSchema);
var User = mongoose.model('User', UserSchema)

필요에 따라서, 필드의 이름도 설정합니다.

mongoose.plugin(timestamps,  {
  createdAt: 'created_at', 
  updatedAt: 'updated_at'
});

스키마 플러그인을 사용하면 이를 달성할 수 있습니다.

»helpers/schemaPlugin.js

module.exports = function(schema) {

  var updateDate = function(next){
    var self = this;
    self.updated_at = new Date();
    if ( !self.created_at ) {
      self.created_at = now;
    }
    next()
  };
  // update date for bellow 4 methods
  schema.pre('save', updateDate)
    .pre('update', updateDate)
    .pre('findOneAndUpdate', updateDate)
    .pre('findByIdAndUpdate', updateDate);
};

및에models/ItemSchema.js 삭제:

var mongoose = require('mongoose'),
  Schema   = mongoose.Schema,
  SchemaPlugin = require('../helpers/schemaPlugin');

var ItemSchema = new Schema({
  name    : { type: String, required: true, trim: true },
  created_at    : { type: Date },
  updated_at    : { type: Date }
});
ItemSchema.plugin(SchemaPlugin);
module.exports = mongoose.model('Item', ItemSchema);

nestjs와 @Schema decorator를 사용하면 다음과 같이 할 수 있습니다.

@Schema({
  timestamps: true,
})

timestamps 옵션은 mongoose에게 createdAt 및 updatedAt 필드를 스키마에 할당하도록 지시합니다.할당된 유형은 날짜입니다.

기본적으로 필드 이름은 createAt 및 updatedAt입니다.

timestamp.createdAt 및 timestamp.updatedAt를 설정하여 필드 이름을 사용자 지정합니다.

mongoose 버전은 4.10.2입니다.

만 것 findOneAndUpdate(직장)

ModelSchema.pre('findOneAndUpdate', function(next) {
  // console.log('pre findOneAndUpdate ....')
  this.update({},{ $set: { updatedAt: new Date() } });
  next()
})
const mongoose = require('mongoose');
const config = require('config');
const util = require('util');

const Schema = mongoose.Schema;
const BaseSchema = function(obj, options) {
  if (typeof(options) == 'undefined') {
    options = {};
  }
  if (typeof(options['timestamps']) == 'undefined') {
    options['timestamps'] = true;
  }

  Schema.apply(this, [obj, options]);
};
util.inherits(BaseSchema, Schema);

var testSchema = new BaseSchema({
  jsonObject: { type: Object }
  , stringVar : { type: String }
});

이제 이 옵션을 사용할 수 있으므로 모든 테이블에 이 옵션을 포함할 필요가 없습니다.

mongo 3.6 이후 '변경 스트림'을 사용할 수 있습니다.https://emptysqua.re/blog/driver-features-for-mongodb-3-6/ #change-filengthttp://https://emptysqua.re/blog/driver-features-for-mongodb-3-6/

이를 사용하려면 'watch' 쿼리를 사용하여 변경 스트림 개체를 생성해야 하며, 각 변경에 대해 원하는 작업을 수행할 수 있습니다.

python 솔루션:

def update_at_by(change):
    update_fields = change["updateDescription"]["updatedFields"].keys()
    print("update_fields: {}".format(update_fields))

    collection = change["ns"]["coll"]
    db = change["ns"]["db"]
    key = change["documentKey"]

    if len(update_fields) == 1 and "update_at" in update_fields:
        pass  # to avoid recursion updates...
    else:
        client[db][collection].update(key, {"$set": {"update_at": datetime.now()}})


client = MongoClient("172.17.0.2")
db = client["Data"]

change_stream = db.watch()

for change in change_stream:
    print(change)
    update_ts_by(change)

주의: change_stream 객체를 사용하려면 mongodb 인스턴스가 'replica set'로 실행되어야 합니다.1노드 레플리카 세트로도 실행할 수 있습니다(스탠드 아론 사용과는 거의 차이가 없습니다).

복제 세트로 mongo를 실행합니다.https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/

복제 세트 구성 vs 스탠드아론:Mongo DB - 스탠드아론 레플리카 세트와 1노드 레플리카 세트의 차이점

사실 뒤에서 하고 있어요.

모든 것이 업데이트에 적합한 경우:

 // All ifs passed successfully. Moving on the Model.save
    Model.lastUpdated = Date.now(); // <------ Now!
    Model.save(function (err, result) {
      if (err) {
        return res.status(500).json({
          title: 'An error occured',
          error: err
        });
      }
      res.status(200).json({
        message: 'Model Updated',
        obj: result
      });
    });

함수를 사용하여 계산된 기본값을 반환합니다.

var ItemSchema = new Schema({
    name: {
      type: String,
      required: true,
      trim: true
    },
    created_at: {
      type: Date,
      default: function(){
        return Date.now();
      }
    },
    updated_at: {
      type: Date,
      default: function(){
        return Date.now();
      }
    }
});

ItemSchema.pre('save', function(done) {
  this.updated_at = Date.now();
  done();
});

날짜/시간 형식을 지정하려면 machinepack-datetime을 사용합니다.

tutorialSchema.virtual('createdOn').get(function () {
    const DateTime = require('machinepack-datetime');
    let timeAgoString = "";
    try {
        timeAgoString = DateTime.timeFrom({
            toWhen: DateTime.parse({
                datetime: this.createdAt
            }).execSync(),
            fromWhen: new Date().getTime()
        }).execSync();
    } catch(err) {
        console.log('error getting createdon', err);
    }
    return timeAgoString; // a second ago
});

머신팩은 익스프레스나 일반 자바스크립트 월드와 달리 클리어 API가 뛰어납니다.

미들웨어가상을 사용할 수 있습니다.다음 예시는 다음과 같습니다.updated_at 추가:

ItemSchema.virtual('name').set(function (name) {
  this.updated_at = Date.now;
  return name;
});

언급URL : https://stackoverflow.com/questions/12669615/add-created-at-and-updated-at-fields-to-mongoose-schemas

반응형