Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
'use strict';
* Module dependencies.
var mongoose = require('mongoose'),
User = mongoose.model('User'),
Profile = mongoose.model('Profile');
* Find profile by username
exports.profile = function(req, res, next, username) {
username: username
.exec(function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('Failed to load User ' + username));
user: user
.exec(function(err, profile) {
if (err) return next(err);
if (!profile) return next(new Error('Failed to load User ' + user));
req.profile = profile;
* Show an profile
*/ = function(req, res) {

This comment has been minimized.

Copy link

@heartforit heartforit commented Jul 29, 2014


just want to drop a short message. That given snippet cannot work at the moment i think.
First of all, you need to understand the concept of Mongodb(Document-oriented schemales noSql database) that means you are not working with relations like in traditional sql databases. That means you can desgin a doucment user, that already contains the user profile. This is possbile because of the doucment desgin of Mongodb(BSON). Another advantage is, to have great performance, because your data is collected diretly in one place so the database has not to do another table or collection lookup.
In your specific case of using mongoose, there is a chance to use schemas on the application level(think about indexies for performance increase).
See also:

And if you want to hold data in two different models (or collections) you can use population:

The reason why you should use an orm-mapper like mongoose is, that mongodb cannot autocast your fields for example. Mongodb is schemales so an value of the field for example zip could have "12345" or 12345. That is in fact a huge diference for the type save mongodb.
Sql-Databases are doing casting by using a predefined table schema. You can also set default values within an traditional sql schema. While mongodb does not have any of this functions like relations, transactions, defaulting, auto field casting and length validation etc.

You also have to think if a classical sql database better fits your use cases. Mongodb scores with great performance and simple schemas to persist just everyting, but if you have data with high need of data safety(transactions) and integrity (relations), you should maybe use a sql database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment