【问题标题】:MeanJS - Adding ArticleID to Comment Mongo CollectionMeanJS - 将 ArticleID 添加到评论 Mongo 集合
【发布时间】:2015-08-15 00:54:49
【问题描述】:

我有 2 个文章和评论集合,我想在创建新评论时将 articleID 添加到评论集合。与UserID自动进入的方式相同。

comment.client.controller.js

// Create new Comment
    $scope.create = function() {
        // Create new Comment object
        var comment = new Comments ({


            details: this.details,
            status: this.status,
            created: this.created,



        });

        // Redirect after save
        comment.$save(function(response) {
            $location.path('comments/' + response._id);

            // Clear form fields
            $scope.status = '';
            $scope.details = '';
            $scope.created = '';
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
        });
    };

comment.server.model.js

var CommentSchema = new Schema({
userName: {
    type: String,
    default: 'To Do',
    required: 'Please fill Comment name',
    trim: true
},
created: {
    type: Date,
    default: Date.now
},
details: {
    type: String,
    trim: true
}
,
user: {
    type: Schema.ObjectId,
    ref: 'User'
},
article: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Article'
}

});

基本上我需要知道的是用户的 ObJectID 来自哪里而没有用户:this.user 或类似您需要的详细信息、状态和创建。我怎样才能让文章自动包含文章 ObjectID?

【问题讨论】:

    标签: javascript mongoose


    【解决方案1】:

    id 将来自路由本身,或者如果您有意在 POST 请求正文中发送它。

    路径中带有文章 ID 的示例: 如果用户对一篇文章(ID 为 123456789)发表评论,它将向 /api/articles/123456789/posts 发出 POST 请求,然后在应用程序的后端,您将定义如下端点:

    app.route('/api/articles/:articleId/posts').post(article.postComment);
    

    注意路由中的:articleId,现在您可以做的是绑定该路由参数以在您的服务器控制器中使用,如下所示:

    app.param('articleId', article.articleById);
    

    articleById 是中间件,将使用 mongoose 查找文章。 articleById 在文章服务器控制器文件中定义。

    然后在您的 postComment 控制器中,您可以使用 req.article 访问 id。

    如果你看一下meanjs中文章模块的服务器路由,你会注意到它已经完成了,所以你可能可以使用req.article来访问文章ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2016-03-16
      • 1970-01-01
      • 2023-04-05
      • 2019-07-23
      • 2014-12-15
      • 1970-01-01
      相关资源
      最近更新 更多