在猫鼬中查找和更新对象 [英] Find and Update Object in Mongoose

查看:54
本文介绍了在猫鼬中查找和更新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的架构:

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 等同于请求接收),但我不知道什么是最好的方法以及如何实现它.

I am trying to implement chat on my app. I am working on my function that will find and update (on each User document, on Chat array with ObjectID as equals being received by request) but i don't know whats the best approach and how to implement it.

对我的端点的请求将给我 ChatID、UserID 和 MessageBody.所以我的两种方法是:1) 按 UserID 查找,然后在 chat array prop 上 findAndUpdate,其中 _idChat 等于 ChatID.2)在集合中找到_idChat等于ChatID的地方然后更新(这应该检索我拥有任何带有ChatID的对象的用户然后更新它)

The request to my endpoint will give me ChatID, UserID, and MessageBody. So my two approaches are: 1) Find by UserID, and then findAndUpdate on chat array prop where _idChat is equals as ChatID. 2) Find in Collection where _idChat is equals as ChatID and then update (this should retrieve me Users that have any object with ChatID and then update it)

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

This is what i am trying to implement (but having nothing being updated):

  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);
    });
  });
});

感谢您的帮助!

推荐答案

这个怎么样?

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);
        }
    )

您将更新符合您条件的确切聊天,因为您将在 $set 命令中使用 $ 运算符.

You are going to update the exact chat that matches your criteria because you'll be using the $ operator on the $set command.

这篇关于在猫鼬中查找和更新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆