Schema within a Schema: Use embedded documents in Mongoose/Mongo
Problems arise when working with embedded array
I previously discussed tips on working with embedded arrays in your Mongoose schema for your MongoDB.
I'd like to cover another tip that is potentially even more useful. Using a Schema inside a Schema which allows you to do updats easily that would be far more complex (and probably more costly in terms of performance) if you just were using a traditional array of objects inside a document inside your collection. Let's set up the two schemas, of which one will be used inside the other.
var Users = new Schema({
_id : ObjectId, //created automatically for us
title : String,
body : String,
date : Date
});
var Room = new Schema({
_id : ObjectId,
name : String,
info : String,
date : Date,
users : [Users],
});
mongoose.model('Rooms', Rooms);
The users
key of the Rooms documents will then be an instance of DocumentArray. This is a special subclassed Array that can deal with casting, and has special methods to work with embedded documents.
Add an embedded document to an array
// create a user in a Room
var Room = new Rooms();
Room.users.push({ name: 'Joe' });
Room.save(function (err) {
if (!err) console.log('Success!');
});
Remove an embedded document
Room.findById(roomId, function (err, room) {
if (!err) {
//we can remove a user by Id rather than looping over an array
room.users(_id).remove();
room.save(function (err) {
// do something
});
}
});
Update an embedded document in an array
Room.findById(roomId, function (err, room) {
if (!err) {
//we can find the user easily and update the name
room.users(_id).name = 'Bob';
room.save(function (err) {
// do something
});
}
});
Using embedded documents in Mongoose will likely make your job of updating data inside an embedded array far easier. Go ahead, try it.