简体   繁体   English

如何根据数组中的条件从参考数组中提取项目?

[英]How to pull items from reference array based on condition in array?

I am working in creating a todo list and one of the action I want users to do is delete all completed todos in one click.我正在创建一个待办事项列表,我希望用户执行的一项操作是一键删除所有已完成的待办事项。 I have my models here, and the code I have, I have been reading trying to figure it out, but can't find it anywhere.我在这里有我的模型,以及我拥有的代码,我一直在阅读试图弄清楚,但在任何地方都找不到。 Thanks in advance.提前致谢。

User Model用户 Model

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  todos: [{
    type: mongoose.Types.ObjectId,
    ref: 'Todo'
  }]
});

Todo model:东都 model:

const TodoSchema = new mongoose.Schema({
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User',
  },
  content: {
    type: String,
    required: true,
  },
  completed: {
    type: Boolean,
    default: false
  },
});

This is what I have now.这就是我现在所拥有的。 I get a "Cast to ObjectId failed for value true at path todos.我在路径 todos 处收到“Cast to ObjectId failed for value true”。

router.delete('/delete/completed', auth, async (req, res) => {
  try {
    const userTodos = await User.update(
      {'_id':req.user.id},
      { $pull: {  'todos': { 'completed': true } } },
      { multi: true }
    );

    if (!userTodos) {
      return res.status(400).send('Server error');
    }

    return res.json({ userTodos });
    //return res.json({msg: 'All completed removed'})
  } catch (err) {
    console.error(err.message);
    return res.status(404).json({ msg: 'Something went wrong, try again' });
  }
});

If you are (as it seems from your code) using mongoose, you could use mongoose's populate feature :如果您(从您的代码看来)使用 mongoose,您可以使用猫鼬的填充功能

const userTodos = await User.find(
  {'_id':req.user.id}).populate('todos', {
    match: {completed: true}
  });

please note, however, that you'll need to delete both the documents in the todos collection, AND the todo reference in the user's todos array.但是请注意,您需要删除 todos 集合中的文档以及用户的 todos 数组中的 todo 引用。 You may consider to remove one side of the reference, see the pros and cons of two-way referencing here您可以考虑删除引用的一侧,在此处查看双向引用的优缺点

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

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