在Mongoose中查找和更新对象

时间:2017-08-26 20:57:07

标签: javascript node.js mongodb mongoose mongodb-query

这是我的架构:

const UserSchema = new mongoose.Schema({
  name: String,
  chats: [{
    lastMessage: String,
    lastUpdate: Date
  }]
});

用户收藏:

{
    "_id" : ObjectId("59987ef42aafc45204ee8bc3"),
    "name" : "Nico",
    "chats" : [ 
        {
            "_id" : ObjectId("599e58265cf2799c07925488")
            "lastMessage": "Test",
            "lastUpdate": "Test"

        }, 
        {
            "_id" : ObjectId("599e59218d4a52c7071f46df")
            "lastMessage": "Hi",
            "lastUpdate": "01/01/2017"
        }
    ]
},
{
    "_id" : ObjectId("59987ef42aafc45204ee8bc3"),
    "name" : "Lucas",
    "chats" : [  
        {
            "_id" : ObjectId("599e59218d4a52c7071f46df")
            "lastMessage": "Hi",
            "lastUpdate": "01/01/2017"
        }
    ]
}

我正在尝试在我的应用上实施聊天。我正在处理我的函数,它将查找并更新(在每个用户文档上,在Chat数组上,ObjectID等于被请求接收),但我不知道最好的方法以及如何实现它。

对我的端点的请求将为我提供ChatID,UserID和MessageBody。 所以我的两种方法是: 1)按UserID查找,然后在_idChat等于ChatID的聊天数组prop上查找和更新。 2)在集合中查找_idChat等于ChatID然后更新(这应该检索我有任何具有ChatID的对象然后更新它的用户)

这是我想要实现的(但没有更新):

  static sendMessage(req: express.Request, res: express.Response) {

    const message = req.body.message;

    const idChat = req.body.idChat;

    const userIds = [req.body.sender, req.body.receiver];

    const updatePromises = [];

    userIds.forEach( userId => {
      updatePromises.push(
        UserDao['updateChat']
        (
          userId, idChat, 
{'$set': {'chats.$.lastMessage': message, 'chats.$.lastUpdate': new Date() }},

      );

    });

    Promise.all(updatePromises)
      .then(values => {
        return res.status(200).json(values);
    }).catch(reason => {
        return res.status(400).json(reason);
    });


userSchema.static('updateChat', (userId, chatId, query) => {
  return new Promise((resolve, reject) => {
    if (!_.isObject(query)) {
      return reject(new TypeError('query is not a valid Object.'));
    }

    if (!_.isString(userId)) {
      return reject(new TypeError('userId is not a valid String.'));
    }

    User
      .update(
        {_id: userId, 'chats._id': chatId},
        {$set: query},
        {upsert: true}
      ).exec((err, updated) => {
      err ? reject(err) : resolve(updated);
    });
  });
});

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这个怎么样?

{
  "error" : {
    "root_cause" : [
      {
        "type" : "remote_transport_exception",
        "reason" : "[aaBiwwv][172.17.0.2:9300][indices:data/write/update[s]]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "failed to execute script",
    "caused_by" : {
      "type" : "script_exception",
      "reason" : "compile error",
      "caused_by" : {
        "type" : "illegal_argument_exception",
        "reason" : "Variable [first] is not defined."
      },
      "script_stack" : [
        "ctx._source.hobbies(first).add(params.new_hob ...",
        "                    ^---- HERE"
      ],
      "script" : "ctx._source.hobbies(first).add(params.new_hobby)",
      "lang" : "painless"
    }
  },
  "status" : 400
}

您将更新符合条件的确切聊天,因为您将在User.update({ _id: request.userId, chats: { $elemMatch: { _id: request.chatId } } }, { $set: { 'chats.$.lastMessage': request.messageBody, 'chats.$.lastUpdate': new Date() }, }, function(err) { // handle error console.log(err); } ) 命令中使用$运算符。