Skip to content

Instantly share code, notes, and snippets.

@tranngoclam
Created April 24, 2016 13:29
Show Gist options
  • Save tranngoclam/b96695d0ebadcf632d86a54bdf1ea46f to your computer and use it in GitHub Desktop.
Save tranngoclam/b96695d0ebadcf632d86a54bdf1ea46f to your computer and use it in GitHub Desktop.
An example for reversing population in Mongoose
// Gets a list of Types
export function index(req, res) {
Type.find({})
.populate('products')
.exec((err, types) => {
if (err) handleErr(err, res);
async.forEach(types, function (type, done) {
Product.find({type: type._id}, '-type -market')
.exec(function (err, products) {
type.products = products;
done(err);
});
}, function (err) {
handleResult(types, res);
});
});
}
function handleErr(err, res, statusCode) {
statusCode = statusCode || 500;
return res.status(statusCode).send(err);
}
function handleResult(entity, res, statusCode) {
statusCode = statusCode || 200;
return res.status(statusCode).json(entity);
}
// Suppose that we have Type and Product model with one-to-many relationship.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TypeSchema = new mongoose.Schema({
id: Schema.Types.ObjectId,
name: String,
products: [{
type: Schema.Types.ObjectId,
ref: 'Product'
}]
}, {versionKey: false});
var ProductSchema = new mongoose.Schema({
id: String,
name: String,
unit: String,
price: Number,
imageUrl: String,
type: {
type: Schema.Types.ObjectId,
ref: 'Type'
},
order: {
type: Schema.Types.ObjectId,
ref: 'Order'
},
market: {
type: Schema.Types.ObjectId,
ref: 'Market'
}
}, { versionKey: false });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment