通过猫鼬更新多个子文档?

编程入门 行业动态 更新时间:2024-10-22 23:26:42
本文介绍了通过猫鼬更新多个子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,我们使用以下模式定义注释树;

Say for example, we're using the following schema to define a comments tree;

{ "_id" : ObjectId("id_here"), "parentComment" : "This is my opinion", "isHidden" : false, "comments" : [ { "comment" : "I disagree with your opinion", "isHidden" : false }, { "comment" : "Test Post", "isHidden" : false }, .... }

因此,如果我们要更新父注释,以将禁止使用的短语的isHidden标志设置为true,我们会这样做;

So, if we were to update the parent comment to set the isHidden flag to true for banned phrases, we'd do so like this;

var userComments = require('mongoose').model("UserComments"); for (let i = 0; i < bannedPhrases.length; i++) { var conditions = { parentComment: bannedPhrases[i] } , update = { isHidden: true} , options = { multi: true }; userComments.update(conditions, update, options, callback); }

现在,考虑子文档注释"(线程注释,多个条目)-我们将如何更新这些注释?

Now, consider the subdocument "comments" (threaded comments, multiple entries) - how would we be able to go about updating these?

推荐答案

我能想到的解决方案是逐个更新嵌套文档.

The solution I can think of is to update the nested document one by one.

假设我们掌握了被禁止的短语,它是一个字符串数组:

Assume we've got hold of the banned phrases, which is an array of strings:

var bannedPhrases = ["censorship", "evil"]; // and more ...

然后我们执行查询以查找具有comments且包含任何bannedPhrases的所有UserComments.

Then we perform a query to find all UserComments which has comments that contain any of the bannedPhrases.

UserComments.find({"commentsment": {$in: bannedPhrases }});

通过使用promises,我们可以一起异步执行更新:

By using promises, we can perform update asynchronously together:

UserComments.find({"commentsment": {$in: bannedPhrases }}, {"commentsment": 1}) .then(function(results){ return results.map(function(userComment){ userCommentments.forEach(function(commentContainer){ // Check if this comment contains banned phrases if(bannedPhrases.indexOf(commentContainerment) >= 0) { commentContainer.isHidden = true; } }); return userComment.save(); }); }).then(function(promises){ // This step may vary depending on which promise library you are using return Promise.all(promises); });

如果您使用 Bluebird JS 是Mongoose的promise库,则可以简化代码:

If you use Bluebird JS is Mongoose's promise library, the code could be simplified:

UserComments.find({"commentsment": {$in: bannedPhrases}}, {"commentsment": 1}) .exec() .map(function (userComment) { userCommentments.forEach(function (commentContainer) { // Check if this comment contains banned phrases if (bannedPhrases.indexOf(commentContainerment) >= 0) { commentContainer.isHidden = true; } }); return userComment.save(); }).then(function () { // Done saving });

更多推荐

通过猫鼬更新多个子文档?

本文发布于:2023-11-22 18:35:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618538.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!