我有一个用户文档,如下所示:
{
"id": "12345",
"favoriteChannels": []
"channels": [
{
"_id": 120398123098120398
"id": "67890",
"count": 1
},
...
]
}
What I want to do is get the channels array, find the top three channels (by count), and push the {id: channel.id, count: channel.count}
objects into User.favoriteChannels.
这是我到目前为止所拥有的:
UserModel.findOne({id:user.id}).then(user => {
user.favoriteChannels = []
let channels = user.channels.sort((a, b) => (a.count < b.count) ? 1 : -1).slice(0,3)
channels.forEach(c => {
user.favoriteChannels.push({id: c.id, count: c.count})
})
user.save(err => { if(err) console.log('Could not save user:', err) })
})
When I execute this, the document doesn't update, and no error is provided: Could not save user: null
.
Interestingly, when I print user.favoriteChannels
, I get:
[ { _id: 98349823749822,
id: '09822',
messageCount: 0 },
{ _id: 98349823749824,
id: '12398',
messageCount: 0 },
{ _id: 98349823749823,
id: '01983',
messageCount: 0 } ]
但是...我以为我删除了这些_id?我究竟做错了什么?是否有比我正在尝试的更好或更简单的解决方案?
编辑:修改代码以使内容更加清晰。
您可以遵循此代码