[英]Update array inside of Mongo document doesn't work
I have a user's collection, each user has a subscription array of objects.我有一个用户的集合,每个用户都有一个订阅对象数组。 I want to add another subscription to that array.
我想向该数组添加另一个订阅。 I'm getting the new subscription, updating it with
findByIdAndUpdate
, but it doesn't add the new subscription, however it shows that the document was updated.我正在获取新订阅,并使用
findByIdAndUpdate
对其进行更新,但它没有添加新订阅,但它显示文档已更新。 I tried several approaches but nothing worked well.我尝试了几种方法,但都没有奏效。 Here is the last approach:
这是最后一种方法:
...
const { user_id } = req.params;
const subscription = req.body; // Getting subscription
const user = await UserModel.findById(user_id).lean().exec(); // Getting user by id
const { push_subscriptions } = user; // Getting subscribtions with destructuring
const updated_subs = [...push_subscriptions, subscription];
// Getting user another time and updating the push_subscriptions array
const updated_user = await UserModel.findByIdAndUpdate(user_id,
{push_subscriptions: updated_subs},
{ new: true }
).exec();
...
Here are the logs of request body and params这是请求正文和参数的日志
// body
{
endpoint: 'https://fcm.googleapis.com/fcm/send/cQ6wlRJ8t-s:APA91bEjqdLMzQLsroJ7zHzdjrzoshdPD8IJy_iIeRa8qV_Yjt6N1jeMUtyMq73wSn9JJT-4WXr_8uwHXttj-XFxHPCPAOqgN7zALsmf_BeIRZowRBTRHf9YH8v3AlcaZXWAIQ0qJNdn',
expirationTime: null,
keys: {
p256dh: 'BBPC5h1QnBMPKMfPacgJu_2RFT7LAejyINh3CvP4pamkrlERr06YpRlSb7RbTUOn6MYW4adG93KfdEWXz68F9iQ',
auth: 'Zl3iaOdBvihXG2QVOb26IQ'
}
}
//params
{ user_id: '5fedc679f414663c693cf549' }
User schema, push_subscriptions part:用户模式,push_subscriptions 部分:
push_subscriptions: {
type: Array,
},
Your query looks good, you can do single query using $push
instead of doing manual process,您的查询看起来不错,您可以使用
$push
进行单个查询,而不是手动处理,
const { user_id } = req.params;
const subscription = req.body;
const updated_user = await UserModel.findByIdAndUpdate(user_id,
{
$push: {
push_subscriptions: subscription
},
{ new: true }
).exec();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.