【发布时间】:2014-12-26 22:43:41
【问题描述】:
我正在尝试使用 Sails.js 和 MongoDB 构建一个支持多级类别的简单应用程序。一个类别可以有许多子类别。因此,在我的Category 模型中,我在其自身类别中设置了一对多关系:
module.exports = {
adapter: 'mongo',
attributes: {
categoryTitle: {
type: 'string',
required: true
},
//owner or parent of the one-to-many relationship
parentCat: {
model: 'category'
},
//sub categories
subCategories: {
collection: 'category',
via: 'parentCat'
},
}};
使用 AngularJS 中的 ng-repeat 指令将类别显示在选择下拉列表中,例如
<select class="selector3" id="categoryParent" ng-model="category.parent">
<option>Choose a category or none</option>
<option ng-repeat="cat in categories" value="{{cat.categoryTitle}}">{{cat.categoryTitle}}</option>
</select>
在 AngularJS CategoryController 中,我使用$scope.category.parent 来捕获所选类别(作为父类别)的值。这一步有效,因为我可以看到console.log($scope.category.parent); 选择的值。
但是,当我将新类别及其父类别一起保存到 MongoDB 时,即使其他字段保存正确,父类别仍为空,如 Mongo 终端所示。 我想问题出在我为在 Sails 中保存新类别而编写的“创建”API 上。您能找出以下代码中可能出错的地方吗?
create: function(req, res, next) {
var params = req.allParams();
// set parent category if exists
if (params.parentCat) {
var parentCategory = Category.findOne({categoryTitle : params.parentCat})
.exec(function(err, category) {
if (err) {
return null; //not found
}
return category; //found, return the category
});
params.parentCat = parentCategory; //set the parent category in params
}
//insert the new category to MongoDB
Category.create(params, function(err, category) {
if (err) {
console.log('category addition failed');
return next(err);
}
console.log('successfully added the category: ' + category.categoryTitle);
res.redirect('/category');
});
} //create
【问题讨论】:
标签: javascript angularjs node.js mongodb sails.js