Javascript 是否可以筛选并仅带回每个notificationType/postId中的一个?
我有一个Javascript 是否可以筛选并仅带回每个notificationType/postId中的一个?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我有一个通知模型和这个模式在这里: const NotificationSchema = new Schema({ type: { type: String, required: true }, createdAt: { type: Number, required: true }, postId: { type: Schema.Types.ObjectId, ref: 'post', required: true
通知
模型
和这个模式
在这里:
const NotificationSchema = new Schema({
type: {
type: String,
required: true
},
createdAt: {
type: Number,
required: true
},
postId: {
type: Schema.Types.ObjectId,
ref: 'post',
required: true
},
recipients: [{
type: Schema.Types.ObjectId,
ref: 'user',
required: true
}]
});
getNotifications(req, res, next) {
const userId = req.params.id;
Notification.find({ recipients: userId })
.sort({ createdAt: 1 })
.then(notifications => res.send(notifications))
.catch(next);
},
我正在构建一个路线控制器,该控制器将获取所有通知
,其中他们是收件人之一,如下所示:
const NotificationSchema = new Schema({
type: {
type: String,
required: true
},
createdAt: {
type: Number,
required: true
},
postId: {
type: Schema.Types.ObjectId,
ref: 'post',
required: true
},
recipients: [{
type: Schema.Types.ObjectId,
ref: 'user',
required: true
}]
});
getNotifications(req, res, next) {
const userId = req.params.id;
Notification.find({ recipients: userId })
.sort({ createdAt: 1 })
.then(notifications => res.send(notifications))
.catch(next);
},
我还想确保,如果有多个通知
具有相同的类型
,例如postAuthorNotification
和相同的postId
,那么它只会返回具有最新createdAt
时间戳的通知
原因是如果一个用户的帖子被评论了20次。每一个都会有一个通知
。不过,我只想向用户发回一个最新的通知
对于猫鼬/猫鼬,这可能吗
谢谢。您已经链接了.sort()
方法,该方法将按createdAt
对结果进行排序。要将结果限制为仅1个,只需将.limit(1)
链接到查询即可
限值的官方文件
方法-