The Definitive Guide to MongoDB
The Definitive Guide to MongoDB, Third Edition
MongoDB The Definitive Guide
MongoDB The Definitive Guide, 2nd Edition
Scaling MongoDB
MongoDB in Action
MongoDB in Action, 2nd Edition
MongoDB and Python
50 Tips and Tricks for MongoDB Developers
MongoDB Applied Design Patterns
MongoDB Basics
Mongoose for Application Development
MongoDB Data Modeling
Practical MongoDB
MongoDB Cookbook, Second Edition
Best practice:
The best practice for a default Mongoose database connection is to open it when the application starts, and keep it open to be re-used. The connection should only need to be closed if your app is being shut down or restarted.
Mongoose provides a simple QueryBuilder interface for when you want to build up the query over multiple steps before executing it at a certain point in your code. Look at the example in the following snippet:
var myQuery = User.find({'name' : 'Simon Holmes'}); myQuery.where('age').gt(18); myQuery.sort('-lastLogin'); myQuery.select('_id name email'); myQuery.exec(function (err, users){ if (!err){ console.log(users); // output array of users found } }); // nebo taky takhle: User .find({'name' : 'Simon Holmes'}) .where('age').gt(18) .sort('-lastLogin') .select('_id name email') .exec(function (err, users){ if (!err){ console.log(users); // output array of users found } });
MongoDB and Mongoose do not support JOIN commands as MongoDB is not a relational database. Mongoose gives you an elegant way to achieve similar functionality by using population.
var userSchema = new mongoose.Schema({ email: String, name: String }); var User = new mongoose.model('User', userSchema); var projectSchema = new mongoose.Schema({ createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, }); var Project = new mongoose.model('Project', projectSchema); Project .findById(req.params.id) .populate('createdBy') // pokud bych chtel jen vybrane pole z dokumentu User: // .populate('createdBy', 'name email') // populate muzu valat na vice poli v dokumentu a retezit je: .populate('contributors', 'name date') // nebo pokud bych vkladal cele dokumenty // .populate('createdBy contributors') .exec(function(err,project) { console.log(project); // createdBy nebude obsahovat jen _id, ale cely objekt User, na ktery _id odkazuje });
You can also populate multiple paths in the parent schema at once. Although, remember that each path is populated by a separate database query.
When populating data with a one-to-many relationship, you may well want to return a subset just like you might with a standard find operation. So far we’ve been using syntactic shortcuts for the populate method, but Mongoose does give you the option of sending a query object for population:
User .find({email: 'pepa@holla.cz'}) .populate({ path: 'contributors', match: { email: /@theholmesoffice\.com/i }, select: 'name lastLogin', options: { limit: 5, sort: 'name' } }) .exec(); // pripoji k dokumentu User pole podle podminky match a options