我有一个文章架构和一个标签架构。我正在尝试将 Tag 对象引用的数组保存到文章。 这是我的文章架构:
var ArticleSchema = new Schema({
....
title: {
type: String,
.....
},
content: {
.....
},
.....
tags: [{
type: Schema.Types.ObjectId,
ref: 'Tag'
}]
});
和标签架构:
var TagSchema = new Schema({
name: {
.....
},
user: {
......
},
count: {
.....
}
});
在前端我有我的控制器。
'use strict';
// Articles controller
angular.module('articles').controller('ArticlesController', [
'$scope', '$stateParams', '$location', 'Authentication', 'Articles', 'Tags', '$filter',
function($scope, $stateParams, $location, Authentication, Articles, Tags, $filter) {
$scope.authentication = Authentication;
// Create new Article
$scope.create = function(isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'articleForm');
return false;
}
var tagsArrays = this.tags.replace(/ /g, '').split(',');
var tagsObjectArray = [];
for (var i = 0; i < tagsArrays.length; i++) {
// Create tag object
var tag = new Tags({
name: tagsArrays[i]
});
tagsObjectArray.push(tag);
saveATag(tag);
//article.tags.push(tag);
}
function saveATag(tempTag) {
tempTag.$save(function(response) {
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
}
// Create new Article object
var article = new Articles.articles({
title: this.title,
content: this.content,
tags: tagsObjectArray
});
// Redirect after save
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
在后端,我有我的文章控制器:
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 {
res.json(article);
}
});
};
当我尝试在文章中保存我的标签数组时出现错误: Cast to Array failed for value "[object Object]" at path "tags" 我环顾四周并尝试了多种方法,但仍然无法将其存储在数据库中。前端和后端的所有路由都设置正确。