简体   繁体   English

使用猫鼬从数组中删除单个项目

[英]Deleting a single item from an array using mongoose

I am new to web development and am making a todo app.我是 Web 开发的新手,正在制作一个待办事项应用程序。 I have the following schema and model:我有以下架构和模型:

const tdSchema = new mongoose.Schema({
  category: {
    type: String,
    required: true,
    unique: true
  },
  tds: {
    type: [{
      type: String
    }]
  }
});
const ToDo = mongoose.model("ToDo", tdSchema);

Here is an example of a document:下面是一个文档示例:

{ "_id" : ObjectId("5f7e2c3d1a151704382ce109"), 
"todos" : [ "Update Resume", "Apply for jobs" ], 
"category" : "Career", "__v" : 0 }

I would like to delete "Update Resume" from the array "todos" while leaving everything else in the document as is.我想从数组“todos”中删除“Update Resume”,同时保留文档中的其他所有内容。

How do I do this using Mongoose JS?我如何使用 Mongoose JS 做到这一点?

First find the document:首先找到文档:

const doc = await ToDo.findOne({ _id: "5f7e2c3d1a151704382ce109" });
console.log(doc);  // optional (used to illustrate how code works)

This will log:这将记录:

{ "_id" : ObjectId("5f7e2c3d1a151704382ce109"), 
"todos" : [ "Update Resume", "Apply for jobs" ], 
"category" : "Career", "__v" : 0 }

From here just access "todos" and remove from it just as you would remove from a typical JavaScript array.从这里只需访问“todos”并从中删除,就像从典型的 JavaScript 数组中删除一样。

doc.todos = doc.todos.filter(e => e !== "Update Resume");

Then save your document:然后保存您的文档:

const updated = await doc.save();
console.log(updated);  // optional (used to illustrate how code works)

And you'll get this in your log:你会在你的日志中得到这个:

{ "_id" : ObjectId("5f7e2c3d1a151704382ce109"), 
"todos" : [ "Apply for jobs" ], 
"category" : "Career", "__v" : 0 }

To build on @Bilal Saleem's answer, if you want to only run one query and ensure it works if multiple people make requests at the same time, you can do this in an update query using the $pull operator.以@Bilal Saleem 的回答为基础,如果您只想运行一个查询并确保它在多人同时发出请求时有效,您可以使用$pull运算符在更新查询中执行此操作。

The $pull operator is used to remove items from a mongodb array, and supports query conditions for the items you wish to pull. $pull 运算符用于从 mongodb 数组中删除项目,并支持您希望拉取的项目的查询条件。

const doc = await ToDo.updateOne(
  { _id: "5f7e2c3d1a151704382ce109" },
  {
    $pull: {
      todos: "Update resume",
    }
  }
);

In the above case, this will $pull from the todos array, and remove any items equal to "Update resume"在上述情况下,这将从todos数组中$pull ,并删除任何等于"Update resume"

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

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