【问题标题】:Find and Update Object in Mongoose [duplicate]在 Mongoose 中查找和更新对象 [重复]
【发布时间】:2018-02-04 13:54:04
【问题描述】:

这是我的架构:

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

我正在尝试在我的应用上实现聊天。我正在研究我的函数,它将查找和更新(在每个用户文档上,在聊天数组上,对象 ID 等于请求接收),但我不知道什么是最好的方法以及如何实现它。

对我的端点的请求将给我 ChatID、UserID 和 MessageBody。 所以我的两种方法是: 1) 按 UserID 查找,然后在 _idChat 等于 ChatID 的聊天数组 prop 上 findAndUpdate。 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);
    });
  });
});

感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    这个怎么样?

    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 命令上使用$ 运算符。

    【讨论】:

    • 我按照你说的进行重构,但没有任何反应 userSchema.static('updateChat', (userId, chatId, query) => { return new Promise((resolve, reject) => { User .update ( {_id: userId, chats: {$elemMatch: {_id: chatId}}}, {$set: query}, {upsert: true} ).exec((err, updated) => { err ? reject(err) : 解决(更新); }); }); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2017-04-04
    • 2021-01-21
    • 2018-02-21
    • 2018-09-10
    • 1970-01-01
    相关资源
    最近更新 更多