Node.js, MongoDB, Express で Mongoose スキーマに created_at と updated_at フィールドを追加する方法
Node.js, MongoDB, Express で Mongoose スキーマに created_at と updated_at フィールドを追加する方法
Mongoose は、Node.js 向けの人気のある ODM (Object Document Mapper) ライブラリです。MongoDB のドキュメントと JavaScript オブジェクトの間のマッピングを簡素化します。Mongoose スキーマは、MongoDB コレクションの構造を定義するために使用されます。
このチュートリアルでは、Node.js、MongoDB、Express を使用して Mongoose スキーマに created_at
と updated_at
フィールドを追加する方法を説明します。
手順
- 必要なパッケージをインストールする
npm install mongoose
- Mongoose スキーマを作成する
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
});
const User = mongoose.model('User', userSchema);
このコードは、name
、email
、password
フィールドを持つ User
スキーマを作成します。また、created_at
と updated_at
フィールドも追加します。これらのフィールドは、ドキュメントが作成された時刻と最後に更新された時刻を自動的に保存します。
- 新しいドキュメントを作成する
const user = new User({
name: 'John Doe',
email: '[email protected]',
password: 'password123',
});
user.save((err) => {
if (err) {
console.error(err);
return;
}
console.log('User created successfully!');
});
このコードは、新しい User
ドキュメントを作成して保存します。created_at
と updated_at
フィールドは、ドキュメントが保存されるときに自動的に設定されます。
User.findById(userId, (err, user) => {
if (err) {
console.error(err);
return;
}
user.name = 'Jane Doe';
user.email = '[email protected]';
user.save((err) => {
if (err) {
console.error(err);
return;
}
console.log('User updated successfully!');
});
});
このコードは、userId
によって識別される既存の User
ドキュメントを見つけ、更新します。ドキュメントが保存されるときに、updated_at
フィールドが自動的に更新されます。
補足
created_at
とupdated_at
フィールドを Mongoose スキーマに追加するには、type: Date
を使用します。created_at
フィールドは、ドキュメントが作成されるときに自動的に設定されます。default: Date.now
オプションを使用して、created_at
とupdated_at
フィールドのデフォルト値を設定できます。
Node.js, MongoDB, Express で Mongoose スキーマに created_at と updated_at フィールドを追加するサンプルコード
プロジェクトのセットアップ
このチュートリアルを実行するには、Node.js と MongoDB がインストールされている必要があります。
- 新しいディレクトリを作成し、そのディレクトリに移動します。
- 次のコマンドを実行して、プロジェクトの依存関係をインストールします。
npm init -y
npm install mongoose
Mongoose スキーマを作成する
次のコードは、User
スキーマを作成し、name
、email
、password
、created_at
、updated_at
フィールドを追加します。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
});
const User = mongoose.model('User', userSchema);
データベースに接続する
次のコードは、MongoDB データベースに接続します。
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });
新しいドキュメントを作成する
次のコードは、新しい User
ドキュメントを作成して保存します。
const user = new User({
name: 'John Doe',
email: '[email protected]',
password: 'password123',
});
user.save((err) => {
if (err) {
console.error(err);
return;
}
console.log('User created successfully!');
});
既存のドキュメントを更新する
次のコードは、userId
によって識別される既存の User
ドキュメントを見つけ、更新します。
User.findById(userId, (err, user) => {
if (err) {
console.error(err);
return;
}
user.name = 'Jane Doe';
user.email = '[email protected]';
user.save((err) => {
if (err) {
console.error(err);
return;
}
console.log('User updated successfully!');
});
});
実行
このコードを実行するには、次のコマンドを実行します。
node index.js
このコードを実行すると、次の出力がコンソールに表示されます。
User created successfully!
User updated successfully!
まとめ
Mongoose スキーマに created_at と updated_at フィールドを追加するその他の方法
timestamps オプションを使用する
Mongoose には、timestamps
オプションを使用して、created_at
と updated_at
フィールドを自動的に作成および更新する機能があります。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
}, { timestamps: true }); // timestamps オプションを追加
const User = mongoose.model('User', userSchema);
ミドルウェアを使用する
Mongoose ミドルウェアを使用して、created_at
と updated_at
フィールドを保存することもできます。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
userSchema.pre('save', function (next) {
if (!this.isNew) {
this.updated_at = Date.now();
}
next();
});
const User = mongoose.model('User', userSchema);
このコードは、pre('save')
ミドルウェアを使用して、ドキュメントが保存される前に updated_at
フィールドを更新します。
カスタムプロパティを使用する
created_at
と updated_at
フィールドを保存するために、カスタムプロパティを使用することもできます。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
createdAt: { type: Date },
updatedAt: { type: Date },
});
userSchema.pre('save', function (next) {
if (!this.createdAt) {
this.createdAt = Date.now();
}
if (!this.updatedAt) {
this.updatedAt = Date.now();
}
next();
});
const User = mongoose.model('User', userSchema);
このコードは、createdAt
と updatedAt
というカスタムプロパティを使用して、created_at
と updated_at
フィールドを保存します。
Mongoose スキーマに created_at
と updated_at
フィールドを追加するには、いくつかの方法があります。どの方法を使用するかは、個々のニーズと好みによって異なります。
node.js mongodb express