【问题标题】:Push to second level array in mongodb with node/express使用 node/express 推送到 mongodb 中的二级数组
【发布时间】:2016-06-19 18:13:09
【问题描述】:

我正在开发一个聊天室,用户可以在其中聊天,根据项目过滤。来自同一项目的用户可以相互交谈。

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

'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"
    }
}

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

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

我们将非常感谢您的帮助。

编辑 1:这是我使用的由 angular 全栈插件生成的帮助功能。

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:正如我在 cmets 中提到的,问题在于 _.Merge 函数没有正确合并对象,尽管它应该能够更新对象。

所以我为 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 错误。

【问题讨论】:

  • 里面有臭味。您传递给thencatch 的函数在您传递它们时被调用。你应该传递一个函数的定义(只是 handleEntityNotFound 或 handleError 或其他东西,没有参数,没有括号)。
  • 我想我明白你在说什么。这是我使用 mean-stack 的第一天,但​​他们正在为我的项目使用不同的其他对象。 showByProject 函数也按预期工作。
  • 更新:尝试了toJsontoObject,它们不起作用。还尝试操作此处提供的代码:mongoosejs.com/docs/documents.html。我现在确定问题出在_.mergesaveUpdates 函数中我创建了一个新函数并尝试使用聊天_id 进行更新,它最多将二级文档中的所有消息替换为第一条消息。 6 小时后,我仍然不知道自己在做什么。

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


【解决方案1】:

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

问题是返回的对象是一个结果集,我在整个结果集上调用 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;
      });
  };
}

【讨论】:

    猜你喜欢
    • 2014-01-28
    • 2019-01-07
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 2017-09-17
    • 2020-03-23
    相关资源
    最近更新 更多