Created
April 24, 2016 13:29
-
-
Save tranngoclam/b96695d0ebadcf632d86a54bdf1ea46f to your computer and use it in GitHub Desktop.
An example for reversing population in Mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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