NodeJS Mongoose Models
Schema : NodeJS Mongoose Schema
Models
All operations are done by Models
Model is created by schema
mongoose.connect('localhost', 'mydb'); var schema = new mongoose.Schema({ name: 'string', size: 'string' }); var Task = mongoose.model('Task', schema); // Documents are instances of model // Save var s = new Task({size: 'small'}); s.save(function(err) { if (err) { return; } // saved });
You can also use create method. it’s same as save
Remove
Task.remove({size: 'midium'}, function(err) { if (err) return; });
Query
select
We can use select column like database
var query = Person.findOne({ 'name.last' : 'Ghost'}); query.select('name occupation'); // SELECT query.exec(function(err, person) { // use exec // person });
Example query(interesting full)
Person .find({ occupation: /host/ }) // Regular Expression .where('name.last').equals('Ghost') .where('age').gt(10).lt(50) .where('likes').in(['a', 'b']) .limit(10) .sort('-occupation') // .sort({occupation: -1}) .select('name occupation') .exec(function(err, results) { });
Documents
document is an instance of Model
Sub Doc
Sub-documents are docs with schemas of their own which are elements of a parents document array
Details are Guide
var childSchema = new Schema({ name: 'string' }); var parentSchema = new Schema({ children: [childSchema] }); var Parent = mongoose.model('Parent', parentSchema); var parent = new Parent({ children: [{ name: 'Lightning' }, { name: 'Sera' }] }); parent.children[0].name = 'Hope'; parent.save(function(err) { });
Finding a sub-document
var doc = parent.children.id(id); // _id