簡體   English   中英

使用 mongoose.find 但每個用戶只能找到一項

[英]use mongoose.find but one item per user

好朋友,我正在為一個項目開發一個API,我需要從數據庫中獲取發送給用戶或用戶發送的最后一條消息。 但在這些消息中,我只想為每個用戶獲取最多 1 條消息,以便在消息收件箱中顯示最后一條消息的預覽,並且在選擇聊天時,將加載每個對話的所有消息。

示例(發送給 Joangel 的所有消息):

來自:Joel,至:Joangel,味精:sdffd

來自:Joel,至:Joangel,味精:234235

來自:Joel,至:Joangel,味精:551

來自:Jorge,至:Joangel,味精:ee werwe

來自:Jorge,至:Joangel,味精:sdffd55

來自:Tony,至:Joangel,味精:heeey

使用 find 時應該返回這個:

來自:Joel,至:Joangel,味精:sdffd

來自:Jorge,至:Joangel,味精:ee werwe

來自:Tony,至:Joangel,味精:heeey

如果你能幫我解決這個問題,我將不勝感激

如果您使用的是 mongoose,那么您應該使用 model.findOne() 方法, findOne 方法文檔的鏈接

基本上你應該做的是創建一個 mongoose 模式和 model,類似於,

const userSchema = new mongoose.Schema({name: String, message: String})

您可以在架構中添加更多項目,然后創建 model,

const User = new mongoose.model("User", userSchema)

每當您想使用 model 執行 function 時,現在將您的用戶添加到 model,您可以查詢它,在您的情況下您必須使用,

User.findOne({conditions which you use to find the specific user}, function(err, foundUser){Here you can do anything with that user which you queried for from your database})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM