使用node / express

时间:2016-03-06 03:11:10

标签: node.js mongodb mean-stack meanjs mean.io

我正在聊天室,用户可以在项目的基础上互相聊天。来自同一项目的用户可以互相交谈。

这是我的聊天模型,其中每个文档都基于项目参考,并且有一个用户参考的消息数组:

'use strict';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var ChatSchema = new mongoose.Schema({
  projectid: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Project'
  },
  messages: [{
    userid: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    message: String,
    date: {
      type: Date,
      default: Date.now
    },
    time: String
  }]
});
export default mongoose.model('Chat', ChatSchema);

现在我正在尝试使用新消息更新消息数组,但过去几个小时我无法这样做。这是我到目前为止所拥有的。

根据我正在使用的项目获取聊天消息:

路线:

router.get('/projectid/:id', controller.showByProject);
router.post('/projectid/:id', controller.insertMessageByProject);

控制器:

// Gets the chat thread based on project id
export function showByProject(req, res) {
  Chat.findAsync({projectid: req.params.id})
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}

// Insert a new message in the chat based on projectid
export function insertMessageByProject(req, res) {
  if (req.body._id) {
    delete req.body._id;
  }
  Chat.findAsync({projectid: req.params.id})
    .then(handleEntityNotFound(res))
    .then(saveUpdates({$push: {messages: req.body}}))
    .then(respondWithResult(res))
    .catch(handleError(res));
}

我从POSTMAN发送的Json对象:

{
    "messages": 
    {
      "userid": "56d7967745ab81322a964927",
      "message": "This is a meesage"
    }
}

OR

{
  "userid": "56d7967745ab81322a964927",
  "message": "This is a meesage"
}

如果我有聊天文档本身的对象ID但是在我的应用程序中,我没有直接引用,我能够更新对象。我也尝试了其他一些方法,但每次我的应用程序返回500错误。

非常感谢您的帮助。

编辑1:以下是我使用的角度全栈插件生成的帮助功能。

function respondWithResult(res, statusCode) {
  statusCode = statusCode || 200;
  return function(entity) {
    if (entity) {
      res.status(statusCode).json(entity);
    }
  };
}

function saveUpdates(updates) {
  return function(entity) {
    var updated = _.merge(entity, updates);
    return updated.saveAsync()
      .spread(updated => {
        return updated;
      });
  };
}

function removeEntity(res) {
  return function(entity) {
    if (entity) {
      return entity.removeAsync()
        .then(() => {
          res.status(204).end();
        });
    }
  };
}

function handleEntityNotFound(res) {
  return function(entity) {
    if (!entity) {
      res.status(404).end();
      return null;
    }
    return entity;
  };
}

function handleError(res, statusCode) {
  statusCode = statusCode || 500;
  return function(err) {
    res.status(statusCode).send(err);
  };
}

编辑2:正如我在评论中提到的,问题在于_.Merge函数没有正确合并对象,尽管它应该能够更新对象。 < / p>

所以我为saveUpdates写了我自己的函数,如下所示:

function saveUpdatesForNewChat(updates) {
  return function(entity) {

    var temp = entity;
    temp[0].messages.push(updates);

    console.log('\ntemp:');
    console.log(require('util').inspect(temp, { depth: null }));
    console.log('\nend of ops\n\n');

    var updated = _.merge(entity, temp);
    console.log('out of merge');
    console.log(require('util').inspect(updated, { depth: null }));
    return updated.saveAsync()
      .spread(updated => {
        return updated;
      });
  };
}

好吧所以我把控制台日志留在里面,这是保存到数据库中的完美对象,但服务器在更新时仍然会返回500错误。

1 个答案:

答案 0 :(得分:0)

OK!所以我自己找到了答案。

问题是返回的对象是结果集,我在整个结果集上调用save。我从返回的结果集中获取了第一个元素,将新消息推送到元素并在其上调用save并开始工作。

以下是代码:

function saveUpdatesForNewChat(updates) {
  return function(entity) {
    var temp = entity[0];
    temp.messages.push(updates);
    var updated = temp;
    return updated.saveAsync()
      .spread(updated => {
        return updated;
      });
  };
}