2017-08-26 103 views
0

更新對象這是我的架構:查找和貓鼬

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

我想實現我的應用程序聊天。我正在研究我的函數,它將查找和更新(在每個用戶文檔上,聊天數組中的ObjectID等於被請求接收),但我不知道最佳方法以及如何實現它。

對我的端點的請求會給我ChatID,UserID和MessageBody。 所以我的兩種方法是: 1)通過UserID查找,然後findAndUpdate聊天數組prop,其中_idChat與ChatID相同。 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); 
    }); 
    }); 
}); 

感謝您的幫助!

回答

0

這個怎麼樣?

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命令符合您的條件的確切聊天。

+0

我重構像你說的我,但什麼也沒發生 userSchema.static( 'updateChat',(用戶ID,chatId,查詢)=> { 返回新的承諾((解析,拒絕)=> { 用戶 .update ( ){_id:userId,chats:{$ elemMatch:{_id:chatId}}}, {$ set:query}, {upsert:true} ).exec((err,updated)=> { err ?reject(err):resolve(updated); }); }); }); –