首页 > 解决方案 > Mongoose/mongodb 如何查找和更新保存在另一个表中的对象/表

问题描述

我将用户保存在用户表和他们所属的公司表中。问题是当我更新用户(通过 id)时,我可以更新用户表中的用户,但无法在公司表中找到/找到该用户。

我希望功能能够工作,当我更新用户时,它会在用户表中更新并在公司表中找到他(它更深一点)并在那里更新他。或者可能有其他更简单的方法可以做到这一点。

这是我的尝试:更新路线,但如果 id 是公司的创建者(所有者),我只能找到公司,而不是我在公司数据库中搜索的用户

//Update user by id
router.patch("/updateUser/:id", auth, log, async (req, res) => {
  const _id = req.params.id;
  const updates = Object.keys(req.body);
  const allowedUpdates = ["firstName", "lastName", "role", "email", "password", "confirmed"];
  const isValidOperation = updates.every((update) =>
    allowedUpdates.includes(update)
  );

  if (!isValidOperation) {
    return res.status(400).send({ error: "Invalid updates!" });
  }

  try {
    const user = await User.findById(_id);

    if (!user) {
      return res.status(404).send();
    }

    updates.forEach((update) => (user[update] = req.body[update]));
    await user.save();


    const company = await Company.find({owner: _id});

    const drivers = company[0].users;

    // const driver = await company[0].users.find()

    // updates.forEach((update) => (user[update] = req.body[update]));
    // await company.save();

    res.send(company[0].users);

  } catch (e) {
    res.status(400).send(e);
  }
});

这是公司模型:

const companySchema = new mongoose.Schema({
    oib: {
        type: Number
    },
    name: {
        type: String
    },
    address:{
        type: String
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    users: [
        {
            user: {
                type: Object
            }
    }
    ],
    orders: [
        {
            order: {
                type: Object
            }
    }
]
}, {
    timestamps: true
})

以及公司字符串的外观

[
    {
        "_id": "6017284c4a0a88712c1d506f",
        "oib": 12345678901,
        "name": "amazon",
        "address": "novska",
        "owner": "60146fbfebc2296410a8cb30",
        "users": [
            {
                "_id": "601728714a0a88712c1d5071",
                "user": {
                    "confirmed": false,
                    "firstLogin": "",
                    "_id": "601728714a0a88712c1d5070",
                    "firstName": "user0",
                    "lastName": "user0",
                    "email": "bvjcunytphhathdayt@upived.online",
                    "password": "user0",
                    "repeatPassword": "user0",
                    "worksFor": "amazon",
                    "tokens": []
                }
            },
            {
                "_id": "60172a260ba15e3e80dbbc75",
                "user": {
                    "confirmed": false,
                    "firstLogin": "",
                    "_id": "60172a260ba15e3e80dbbc74",
                    "firstName": "user1",
                    "lastName": "user1",
                    "email": "bvjcunytphhathfdfyt@upived.online",
                    "password": "user1",
                    "repeatPassword": "user1",
                    "worksFor": "amazon",
                    "tokens": []
                }
            }
        ],
        "orders": [
            {
                "_id": "60174019a9e5dd5028d0f495",
                "order": {
                    "completed": true,
                    "processed": true,
                    "_id": "60174019a9e5dd5028d0f494",
                    "origin": "Novska, Croatia",
                    "destination": "Kutina, Croatia",
                    "company": "amazon",
                    "owner": "60146fbfebc2296410a8cb30"
                }
            }
        ],
        "createdAt": "2021-01-31T21:59:40.520Z",
        "updatedAt": "2021-01-31T23:41:13.803Z",
        "__v": 3
    }
]

谢谢

标签: javascriptnode.jsmongodbmongoose

解决方案


据我了解,您保留了重复数据,mongodb 不支持使用此操作,因为您根本不应该这样做(它真的非常糟糕),而不是重复只保留 id。您节省空间和操作。


推荐阅读