gpt4 book ai didi

javascript - Mongoose - 无法填充路径通知排序。因为它是文档数组的子属性

转载 作者:数据小太阳 更新时间:2023-10-29 04:48:55 25 4
gpt4 key购买 nike

我有一个非常简单的 mongo 方案,我正在使用 mongoose 访问

我可以使用填充将用户名和名字映射到每个通知的发件人字段,问题是我似乎无法对日期字段进行任何排序

使用这段代码我得到一个错误

MongooseError: Cannot populate with sort on path notifications.from because it is a subproperty of a document array

是否有可能以不同的方式或更新的方式(深度填充、虚拟)做到这一点?我正在使用 Mongoose 5。

我宁愿不使用 vanilla javascript 之后对对象进行排序或创建一个单独的模式

var UserSchema = new Schema({  
username: String,
firstname: String,
notifications: [
{
from: { type: Schema.Types.ObjectId, ref: 'User'},
date: Date,
desc: String
}
]
});

app.get('/notifications', function(req, res) {
User.findOne({ _id: req._id }, 'notifications')
.populate({
path: 'notifications.from',
populate: {
path: 'from',
model: 'User',
options: { sort: { 'notifications.date': -1 } }
}
})
.exec(function(err, user) {
if (err) console.log(err)
})
});

关于 Mongo 的可能重复项已经有将近 2 年的历史了。我想问在 Mongoose 中是否有更新的或不同的方法来执行此操作,因为它自 2016 年以来发生了一些变化,具有更新的功能。

最佳答案

来自 Mongoose V5.0.12 常见问题解答:http://mongoosejs.com/docs/faq.html#populate_sort_order

Q. I'm populating a nested property under an array like the below code:

new Schema({ arr: [{ child: { ref: 'OtherModel', type: Schema.Types.ObjectId } }] });

.populate({ path: 'arr.child', options: { sort: 'name' } }) won't sort by arr.child.name?

A. See this GitHub issue. It's a known issue but one that's exceptionally difficult to fix.

很遗憾,目前还不可能,

实现此目的的一种方法是简单地使用 javascript 的原生 sort 在获取后对通知进行排序。

.exec(function(err, user) {
if (err) console.log(err)

user.notifications.sort(function(a, b){
return new Date(b.date) - new Date(a.date);
});

})

关于javascript - Mongoose - 无法填充路径通知排序。因为它是文档数组的子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49304063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com