簡體   English   中英

無法使用貓鼬推送到數組

[英]Can't push to array using mongoose

我有代碼,基本上仍然是MEANJS樣板,並且在文章中添加了一段以供評論。 我的注釋策略是使用一個非常簡單的注釋模型(具有用戶對象,內容字符串和喜歡的數字)以express / comments /:commentId公開路由。 我擴展了文章模型,以包括用於評論的對象ID數組,並且在加載文章時,我的有角資源將調用/ comments /:commentId來檢索由該數組指定的評論列表。 以下是我的服務器代碼

/* below is comments.server.controller.js */

/* THIS IS NEVER GETTING CALLED */
exports.updateArticleComments = function(req, res){
  Article.findById(req.comment.article).populate('user', 'displayName').exec(function(err, article){
    console.log(article);
    if (err) return res.json(err);
    if (!article) res.json({err: 'oops!'}); //handle this ish
    article.comments[article.comments.length] = req.comment._id;
    article.save(function(err, article){
      if (err){
        console.log('error');
      } else {
        res.json(article);
      }
    });
  });
};

exports.commentsByID = function(req, res, next, id) {
  Comment.findById(id).populate('user', 'displayName').exec(function(err, comment) {
    if (err) return next(err);
    if (!comment) return next(new Error('Failed to load comment ' + id));
    req.comment = comment;
    next();
  });
};

/* end comments.server.controller.js */

/* begin articles.server.routes.js */

'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users.server.controller'),
  articles = require('../../app/controllers/articles.server.controller'),
  comments = require('../../app/controllers/comments.server.controller');

module.exports = function(app) {
  // Article Routes
  app.route('/articles')
    .get(articles.list)
    .post(users.requiresLogin, articles.create);

  app.route('/articles/:articleId')
    .get(articles.read)
    .put(users.requiresLogin, articles.hasAuthorization, articles.update)
    .post(comments.createComment, comments.updateArticleComments)
    .delete(users.requiresLogin, articles.hasAuthorization, articles.delete);

  // Finish by binding the article middleware
  app.param('articleId', articles.articleByID);
};

/* end articles.server.routes.js */

除了exports.updateArticleComments函數之外,所有內容(我的意思是所有內容)均有效。 我認真地寫了5種不同的函數,嘗試了lodash的_extend以及許多其他技術。 我不明白為什么注釋數組永遠不會被填充。 有人有什么建議嗎?

編輯:被要求共享createComment,所以在這里

exports.createComment = function(req, res, next){
  var comment = new Comment({content: req.body.content, article: req.body.articleId});
  comment.user = req.user;
  comment.save(function(comment, err){
    if (err){
       return res.jsonp(err);
    } else {
        req.comment = comment;
        next();
    }
  });
};
Article.update({_id: 'VAL' }, {
  $push: { 
    'comments' : req.comment._id }},{upsert:true},
    function(err, data) { });

您是否嘗試過推送方法? 我也很好奇,如果注釋_id的值又回來了並且不是未定義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM