简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z,$从嵌套数组中拉出一个元素并根据元素的存在更新文档

[英]Mongoose, $pull an element from nested array and update document based on the presence of the element

I am working on a mongoose schema similar to this:我正在研究类似于此的 mongoose 架构:

const actionSchema = {
    actions: {
        type: [{
            actionName: {
                type: String,
                required: true
            },
            count: {
                type: Number,
                default: 0,
                required: true
            },
            users: [{
                type: Schema.Types.ObjectId,
                ref: 'User'
            }]
        }]
    }};

It is a nested schema of a post schema.它是后期模式的嵌套模式。 Here, actions are dynamically generated and number of people does that action are maintained by count and their identity is maintained by users array.在这里,动作是动态生成的,执行该动作的人数由计数维护,他们的身份由用户数组维护。

As you see, actions is an array of objects which further contain users array.如您所见,actions 是一个对象数组,其中还包含 users 数组。 I want to check if a provided user id is present in any of the action object and then remove it from array and also reduce the count.我想检查在任何操作 object 中是否存在提供的用户 ID,然后将其从数组中删除并减少计数。

Being totally new to mongoose and mongodb, one simple way I see is to find the post using Post.findById() which has to be updated, run js loops, update the post and call .save() .作为 mongoose 和 mongodb 的新手,我看到的一种简单方法是使用必须更新的Post.findById()找到帖子,运行 js 循环,更新帖子并调用.save() But it can be very costly when users array has thousands of user ids.但是当 users 数组有数千个用户 ID 时,它可能会非常昂贵。 I tried .update() but can't understand how to use it in this case.我试过.update()但不明白在这种情况下如何使用它。

How about adding a method to the Post Model (like postSchema.methods.removeUserAction )?如何在 Post Model 中添加一个方法(如postSchema.methods.removeUserAction )? This gives access to document from this and allows to update the document and thus call .save() .这允许从this访问文档并允许更新文档并因此调用.save() Does it loads the full document to the client node application?它是否将完整文档加载到客户端节点应用程序?

So please suggest the right way.所以请建议正确的方法。 Thank you.谢谢你。

You should simplify your model, for example例如,您应该简化 model

// Model - Actions Model

const actionSchema = {
   actionName: {
       type: String,
       required: true
   },
   user: {
       type: Schema.Types.ObjectId,
       ref: 'User'
   }
};

And you can easily get the total actions via Model.count() , get specific action count with Model.count({ actionName: 'action name'}) , and removing entries with Model.delete(condition) .您可以通过Model.count()轻松获取总操作数,使用Model.count({ actionName: 'action name'})获取特定操作计数,并使用Model.delete(condition)删除条目Unless there's a reason why you have it modeled this way.除非有理由让您以这种方式建模。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM