【发布时间】:2019-11-17 23:50:43
【问题描述】:
每个消息文档都有一个 messageTrackingId。我想返回所有消息,但排除具有相同 messageTrackingId 的文档。例如,如果我的表中有 4 个文档,其中 3 个具有相同的 messageTrackingId 值,那么 Messages.find() 应该只返回 2 个文档。
我正在尝试使用 distinct 来仅返回唯一文档,这样我就不会得到具有相同 messageTrackingId 的重复文档。目前邮递员没有退回任何文件。
如果我改变了
Messages.find({query}).distinct('messageTrackingId')
至
Messages.find(query)
然后它返回所有接收者 ID 的文档。但是当我添加 distinct 时,我没有得到任何结果。
app.get('/api/messages',(req, res, next)=>{
query = {};
inbox = false;
messageId = false;
if(req.query.recipientId){
query = { recipientId: req.query.recipientId }
inbox = true;
Messages.aggregate(// Pipeline
[
// Stage 1
{
$group: {
_id: "$messageTrackingId",
message : { $addToSet: '$message' },
recipientId : { $addToSet: '$recipientId' },
creator : { $addToSet: '$creator' },
messageTrackingId : { $addToSet: '$messageTrackingId' },
}
},
// Stage 2
{
$project: {
_id: 1,
message: { $arrayElemAt: ["$message", 0 ] },
recipientId: { $arrayElemAt: ["$recipientId", 0 ] },
creator: { $arrayElemAt: ["$creator", 0 ] },
messageTrackingId: { $arrayElemAt: ["$messageTrackingId", 0 ] }
}
}
])
消息模型
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const messagingSchema = mongoose.Schema({
creator: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
recipient: { type: String, required: true },
recipientId: { type: String, required: true },
message: { type: String, required: true },
subject: { type: String, required: true },
creationDate: { type: Date, required: true },
messageTrackingId: { type: String }
// readDate: { type: Date, required: true }
});
module.exports = mongoose.model("Messages", messagingSchema);
【问题讨论】:
-
“如果我的表中有 4 个文档,其中 3 个具有相同的 messageTrackingId 值,那么 Messages.find() 应该只返回 2 个文档。” - 3 个中的哪一个应该被退回?
-
只有 2 个文档会在该场景中返回,因为其中 3 个具有匹配的 messageTrackingId。我只需要每个 messageTrackingId 一个文档来引用该 messageTrackingID。
-
那么如果5个文档都有相同的messageTrackingIds,只取第一个?按什么属性排序?
-
排序没有偏好。只要其中一个返回,它使用相同的 messageTrackingId 抓取哪个文档都没有关系。当我为所有相关消息执行 GET 时,我只需要稍后引用该值。