通过移除数组中包含NodeJs和Mongoose的元素来更新值

cfh9epnr  于 2022-11-13  发布在  Go
关注(0)|答案(3)|浏览(141)

我希望实现的功能:在前端,我有所有业主的列表中的复选框。.添加的业主已经选中。.我怎么能实现,如果我取消选中一些业主ID,并检查像2个新的业主,所以我删除未选中的业主,并添加新的“选中”之一。
我有一个用户模型:

const UserSchema = new mongoose.Schema({
  email: { type: String, required: true, min: 6, max: 255 },
  password: { type: String, required: true, min: 4, max: 1024 },
  role: { type: String, required: true, default: "User" },
  owners: [
    {
      type: Schema.Types.ObjectId,
      ref: "Owners",
      required: false,
    },
  ],
});

每个usser都有一个所有者数组

我使用以下查询PUT METHOD将所有者添加到特定用户:

exports.addOwnerToUser = async (req: Request, res: Response) => {
  try {
    let ObjectID = require("mongodb").ObjectID;
    const mongoose = require("mongoose");

    const user = {
      email: req.body.email,
      ownerId: req.body.ownerId,
    };

        const updatedUser = await User.findOneAndUpdate(
  { _id: req.params.userId, owners: { $ne: req.body.ownerId } },
  { $push: { owners: { $each: req.body.ownerId } } },
  { new: true, useFindAndModify: false }
);

    res.status(201).json({ sucess: true, msg: "User updated sucessfully" });
  } catch (err) {
    res.status(404).json(err);
  }
};

**2.)**如果我在前端取消检查所有者,我如何才能实现从所有者数组中删除它?

mrwjdhj3

mrwjdhj31#

您可以使用$pullAll
此操作将从scores数组中删除所设置值的所有示例

const updatedUser = await User.findOneAndUpdate(
  { _id: req.params.userId, owners: { $ne: req.body.ownerId } },
  { $pullAll: { owners: ["630367b3c8e06afa0339a609"] } },
);

您可以阅读文档HERE

8cdiaqws

8cdiaqws2#

我是这样解决的:

exports.addOwnerToUser = async (req: Request, res: Response) => {
  try {
    let ObjectID = require("mongodb").ObjectID;
    const mongoose = require("mongoose");

    const user = {
      email: req.body.email,
      ownerId: req.body.ownerId,
    };

    const updatedUser = await User.findOneAndUpdate(
      { _id: req.params.userId },
      { $push: { owners: { $each: req.body.ownerId } } },
      { new: true, useFindAndModify: false } */

      { _id: req.params.userId },
      { $set: { owners: req.body.ownerId } },
      { arrayFilters: [{ owners: { $eq: user.ownerId } }], multi: true }
    );

    res.status(201).json({ sucess: true, msg: "User updated sucessfully" });
  } catch (err) {
    res.status(404).json(err);
  }
};
nkkqxpd9

nkkqxpd93#

$push$pull操作在更新查询的单个属性中是不可能的,
我有三个建议:
1.如果owners数组限制为最多10个元素,则从前端获取所有者ID的整个数组并更新该数组,因此不需要推送和拉取操作
1.执行两个单独的查询,第一个针对推元素,第二个针对拉元素
1.尝试从MongoDB 4.2开始执行update with aggregation pipeline查询,让我们通过一个示例来了解:
考虑一个文档:

[
  {
    _id: ObjectId("5a934e000102030405000000"),
    owners: [
      ObjectId("5a934e000102030405000000")
    ]
  }
]

考虑输入变量:

let _id = "5a934e000102030405000000";
let addOwners = ["5a934e000102030405000001", "5a934e000102030405000002"];
let removeOwners = ["5a934e000102030405000000"];

让我们准备查询,

  • 将更新部分 Package 在数组括号中
  • $filter用于迭代owners数组的循环,并删除removeOwners数组变量中提供的id
  • $concatArrays将上面过滤过的数组去掉id后进行concat,并添加addOwners数组变量
const updatedUser = await User.findOneAndUpdate(
  { _id: _id },
  [{
    $set: {
      owners: {
        $concatArrays: [
          {
            $filter: {
              input: "$owners",
              cond: { $not: { $in: ["$$this", removeOwners] } }
            }
          },
          addOwners
        ]
      }
    }
  }],
  { new: true }
);

Playground

相关问题