mongoose
モンゴーススキーマ
サーチ…
基本スキーマ
基本的なユーザースキーマ:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
name: String,
password: String,
age: Number,
created: {type: Date, default: Date.now}
});
var User = mongoose.model('User', userSchema);
スキーマの種類 。
スキーマメソッド
メソッドはスキーマに設定して、そのスキーマに関連する作業を支援し、スキーマを整理しやすくすることができます。
userSchema.methods.normalize = function() {
this.name = this.name.toLowerCase();
};
使用例:
erik = new User({
'name': 'Erik',
'password': 'pass'
});
erik.normalize();
erik.save();
スキーマ統計
スキーマ統計は、モデルによって直接呼び出されるメソッドです(スキーマメソッドとは異なり、Mongooseドキュメントのインスタンスによって呼び出される必要があります)。スキーマのstaticsオブジェクトに関数を追加することによって、静的をスキーマに割り当てます。
カスタムユースを構築するためのユースケースの例を次に示します。
userSchema.statics.findByName = function(name, callback) {
return this.model.find({ name: name }, callback);
}
var User = mongoose.model('User', userSchema)
User.findByName('Kobe', function(err, documents) {
console.log(documents)
})
ジオオブジェクトスキーマ
点、線ストリング、ポリゴンなどのジオオブジェクトを操作するのに便利な汎用スキーマ。 MongooseとMongoDBの両方がGeojsonをサポートしています 。
ノード/エクスプレスでの使用例:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Creates a GeoObject Schema.
var myGeo= new Schema({
name: { type: String },
geo : {
type : {
type: String,
enum: ['Point', 'LineString', 'Polygon']
},
coordinates : Array
}
});
//2dsphere index on geo field to work with geoSpatial queries
myGeo.index({geo : '2dsphere'});
module.exports = mongoose.model('myGeo', myGeo);
現在の時間と更新時間の保存
この種のスキーマは、挿入時間または更新時間によってアイテムのトレースを保持したい場合に便利です。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Creates a User Schema.
var user = new Schema({
name: { type: String },
age : { type: Integer},
sex : { type: String },
created_at: {type: Date, default: Date.now},
updated_at: {type: Date, default: Date.now}
});
// Sets the created_at parameter equal to the current time
user.pre('save', function(next){
now = new Date();
this.updated_at = now;
if(!this.created_at) {
this.created_at = now
}
next();
});
module.exports = mongoose.model('user', user);
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow