connect() vs createConnection()

My understanding on the official documentation is that generally when there is only one connection mongoose.connect() is use, whereas if there is multiple instance of connection mongoose.createConnection() is used. Yes. To be exact, .connect() creates actually a pool of sockets/connections (defined in poolSize in the connection settings, the default is 5) it keeps open, so …

Read more

Creating a Foreign Key relationship in Mongoose

Check Updated code below, in particular this part: {type: Schema.Types.ObjectId, ref: ‘Ingredient’} var mongoose = require(‘mongoose’); var Schema = mongoose.Schema; var IngredientSchema = new Schema({ name: String }); module.exports = mongoose.model(‘Ingredient’, IngredientSchema); var mongoose = require(‘mongoose’); var Schema = mongoose.Schema; var RecipeSchema = new Schema({ name: String, ingredients:[ {type: Schema.Types.ObjectId, ref: ‘Ingredient’} ] }); module.exports …

Read more

Node.js – Creating Relationships with Mongoose

It sounds like you’re looking to try the new populate functionality in Mongoose. Using your example above: var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; SubdomainSchema = new Schema name : String CustphoneSchema = new Schema phone : String subdomain : { type: ObjectId, ref: ‘SubdomainSchema’ } The subdomain field will be is updated with an …

Read more

How to populate a sub-document in mongoose after creating it?

In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: ‘User’ }). Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate as usual (e.g. populate(‘comments.created_by’)) Proof of concept …

Read more