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();
स्कीमा स्टेटिक्स
स्कीमा स्टैटिक्स एक मॉडल द्वारा सीधे लागू किए जा सकने वाले तरीके हैं (स्कीमा विधियों के विपरीत, जिन्हें एक मॉनसून दस्तावेज़ के उदाहरण द्वारा लागू करने की आवश्यकता होती है)। आप स्कीमा के 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 स्कीमा
एक सामान्य स्कीमा जो कि भू-पिंडों जैसे बिंदुओं, लिनस्ट्रेस और बहुभुजों के साथ काम करने के लिए उपयोगी है। 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);