I\'ve seen many examples about mongoose and relations, but how can I create a reference to another entity into a custom field ?
var mongoose = require(\'mongoose
Mongoose is set up more for direct object relations. Rather than linking your Book
object to a slug for the Author
object, it would suit better to link to the Author's _id
property automatically created by Mongoose.
var Author = mongoose.model('Author', new mongoose.Schema({
name: String
});
var Book = mongoose.model('Book', new mongoose.Schema({
title: String
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' }
});
You can then save an Author
as the author
of the Book
object by either saving book.author = author
or book.author = author._id
. Mongoose will automatically serialize the data when saving.
var author = new Author();
author.name = 'Hank Brekke';
var book = new Book();
book.title = 'My Book';
book.author = author;
book.save();
When pulling the book object, you can have Mongoose automatically populate the author
property, which by default it will not, by adding the .populate('author')
modifier before calling .exec()
Book.findOne({ /* query */}).populate('author').exec(function(error, book) {
var author = book.author;
});
http://mongoosejs.com/docs/populate.html