【发布时间】:2014-12-03 07:09:51
【问题描述】:
在模型中获取嵌套对象时遇到问题。 我有一家样板餐厅,我在其中引用了一篇文章。这只是一个演示,让我测试它是如何工作的,但我没有得到它.. :(
啊..我正在使用meanjs..
这是我的餐厅模型..
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Restaurant Schema
*/
var RestaurantSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Restaurant name',
trim: true
},
desc: {
type: String,
default: 'description is here'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
article: {
type: Schema.ObjectId,
ref: 'Article'
}
});
mongoose.model('Restaurant', RestaurantSchema);
这是我的文章模型。
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
}
});
mongoose.model('Article', ArticleSchema);
这两个方法在nodejs后端餐厅控制器中:
exports.list = function(req, res) { Restaurant.find().sort('-created').populate('article').exec(function(err, restaurants) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(restaurants);
}
});
};
exports.restaurantByID = function(req, res, next, id) { Restaurant.findById(id).populate('article').exec(function(err, restaurant) {
if (err) return next(err);
if (! restaurant) return next(new Error('Failed to load Restaurant ' + id));
req.restaurant = restaurant ;
next();
});
};
然后我有一个角度控制器方法来保护一家新餐厅和一篇文章,该方法正在运行。当我访问"http://localhost:3000/#!/articles"。但是,当我试图获得例如标题时,它不起作用。
我正在以这种方式创建我的餐厅和文章:
// Create new Restaurant
$scope.create = function () {
// Create new Restaurant object
var newArticle = new Articles({
title: this.articleTitle
});
newArticle.$save();
var restaurant = new Restaurants({
name: this.name,
desc: this.description,
article: newArticle._id
});
// Redirect after save
restaurant.$save(function (response) {
$location.path('restaurants/' + response._id);
// Clear form fields
$scope.name = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
这是在我的创建视图中:
<div class="controls">
<input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>
<input type="text" data-ng-model="articleTitle" id="article" class="form-control" placeholder="artikel" required>
<input type="text" data-ng-model="description" id="description" class="form-control" placeholder="desription" required>
</div>
这是在我的列表视图中
<h4 class="list-group-item-heading" data-ng-bind="restaurant.name"></h4>
<h3 class="list-group-item-heading" data-ng-bind="restaurant.article"></h3>
<h3 class="list-group-item-heading" data-ng-bind="restaurant.desc"></h3>
描述在浏览器中可见,但没有关于文章的可见内容。如何在餐厅对象中获取有关文章的信息?
可能,这很容易,但我没有发现它..
先谢谢了..
【问题讨论】:
-
有趣的是我也没有得到文章的ID..
标签: node.js angularjs mongodb express mongoose