FAQ

Q. Why don’t my changes to arrays get saved when I update an element directly?

  1. doc.array[3] = 'changed';
  2. doc.save();

A. Mongoose doesn’t create getters/setters for array indexes; without them mongoose never gets notified of the change and so doesn’t know to persist the new value. The work-around is to use MongooseArray#set available in Mongoose >= 3.2.0.

  1. // 3.2.0
  2. doc.array.set(3, 'changed');
  3. doc.save();
  4. // if running a version less than 3.2.0, you must mark the array modified before saving.
  5. doc.array[3] = 'changed';
  6. doc.markModified('array');
  7. doc.save();

Q. Why doesn’t mongoose allow me to directly assign schemas to paths?

  1. var userSchema = new Schema({ name: String });
  2. new Schema({ user: userSchema })

A. Schemas have a one-to-one mapping with documents. Documents have save and remove methods along with their own pre and post hooks which would lead to code like the following:

  1. doc.user.save(); // ?
  2. doc.user.remove();// ?
  3. doc.save()

We’ve felt that this api would be more confusing than helpful. The counter argument is that arrays of sub-documents already have this functionality, but at best this too leads to confusion (calling save on a sub-document is a no-op and exists only to support pre save hooks). In the future this is likely to be revisited.


Q. How can I enable debugging?

A. Set the debug option to true:

  1. mongoose.set('debug', true)

All executed collection methods will log output of their arguments to your console.


Q. My save() callback never executes. What am I doing wrong?

A. All collection actions (insert, remove, queries, etc) are queued until the connection opens. It is likely that an error occurred while attempting to connect. Try adding an error handler to your connection.

  1. // if connecting on the default mongoose connection
  2. mongoose.connect(..);
  3. mongoose.connection.on('error', handleError);
  4. // if connecting on a separate connection
  5. var conn = mongoose.createConnection(..);
  6. conn.on('error', handleError);

Q. Should I create/destroy a new connection for each database operation?

A. No. Open your connection when your application starts up and leave it open until the application shuts down.


Something to add?

If you’d like to contribute to this page, please visit it on github and use the Edit button to send a pull request.