- Mongoose 里,一切都始于Schema。
- Schema定义:
- 允许使用的 SchemaTypes 有String, Number, Date, Buffer, Boolean, Mixed, ObjectId, Array, Decimal128, Map
var Schema = mongoose.Schema;
var kittySchema = new Schema({name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
kittySchema.methods.speak = function () {var greeting = this.name? "Meow name is " + this.name: "I don't have a name";console.log(greeting);
}
var felyne = new Kitten({ name: 'Felyne' });
felyne.speak();
kittySchema.statics.findByName = function(name, cb) {return this.find({ name: new RegExp(name, 'i') }, cb);
};
Kitten.findByName('Felyne', function(err, kits) {console.log('调用静态方法');console.log(kits);
});
kittySchema.query.byName = function(name) {return this.find({ name: new RegExp(name, 'i') });
};
Kitten.find().byName('Felyne').exec(function(err, kits) {console.log('调用查询助手');console.log(kits);
});