수색…


기본 스키마

기본 사용자 스키마 :

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();

스키마 통계

스키마 통계 (Schema Statics)는 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)
})

GeoObjects 스키마

점, 선 스트링 및 다각형과 같은 지형 객체로 작업하는 데 유용한 일반 스키마. MongooseMongoDBGeojson을 지원 합니다 .

노드 / 익스프레스 에서의 사용 예 :

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