Learning MeanJS and encountering Mongoose issues. Two models are in question:
CategorySchema:
- name: String, default:'', required: 'Please fill Category name', trim: true
- slug: String, default:'', trim: true, unique: true
- created: Date, default: Date.now
- user: Schema.ObjectId, ref: 'User'
- articles: [Schema.ObjectId, ref: 'Article']
ArticleSchema:
- created: Date, default: Date.now
- category: Schema.ObjectId, ref: 'Category'
- title: String, default:'', trim: true, required: 'Title cannot be blank'
- slug: String, default:'', trim: true, unique: true
- content: String, default:'', trim: true
- user: Schema.ObjectId, ref: 'User'
Saving articles with the following function:
exports.create = function(req, res) {
var article = new Article(req.body);
article.user = req.user;
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Category.findById(article.category).exec(function(err, category) {
category.articles.push(article.category);
category.save(function(err, category) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
});
}
});
};
All is saving correctly and the object structure appears as follows:
{
"_id" : ObjectId("55b73bf97aa70c2c083655b0"),
"user" : ObjectId("55b115f35c7a03cc0e59d821"),
"articles" : [
ObjectId("55b73c017aa70c2c083655b2"),
ObjectId("55b73ee20bab5e8c0c7eadca")
],
"created" : ISODate("2015-07-28T08:23:21.562Z"),
"slug" : "motocycles",
"name" : "Motocycles",
"__v" : 2
}
However, upon attempting to retrieve data using .populate('articles'), unexpected behavior occurs:
exports.list = function(req, res) {
Category.find().sort('-created').populate('user', 'displayName').populate('articles').exec(function(err, categories) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(categories);
}
});
};
The length now returns 0, ObjectIds disappear, and access to article properties is lost. This occurrence raises questions on why this might be happening.
Additional edit:
mongoose.model('Article', ArticleSchema);
mongoose.model('Category', CategorySchema);