【问题标题】:Mongoose relations add multiple Id to a Schema (many to One)Mongoose 关系将多个 Id 添加到 Schema(多对一)
【发布时间】:2022-02-15 14:54:05
【问题描述】:

所以我想将许多车辆引用到我的客户端架构,但我不知道该怎么做。

这是我的架构:

const { Schema, model, Types } = require('mongoose');
const ClientSchema = new Schema(
  {
    id: {
      type: String,
      unique: true,
    },
    firstName: {
      type: String,
      required: [true, 'Client First Name is required.'],
    },
    lastName: {
      type: String,
      required: [true, 'Client Last Name is required.'],
    },
    email: {
      type: String,
      required: [true, 'Client Email Address is required.'],
      unique: true,
    },
    company: {
      type: String,
      required: false,
    },
    phone: {
      type: String,
      required: [true, 'Client Phone Number is required.'],
      unique: true,
    },
    country: {
      type: String,
      required: [true, 'Client Country Location is required.'],
      default: 'Switzerland',
    },
    street: {
      type: String,
      required: [true, 'Client Street is required.'],
    },
    city: {
      type: String,
      required: [true, 'Client City Location is required.'],
    },
    zip: {
      type: String,
      required: [true, "Client's Country Zipcode is required."],
    },
    vehicles: [
      {
        type: Types.ObjectId,
        ref: 'vehicle',
      },
    ],
  },
  {
    timestamps: true,
  }
);

module.exports = model('Client', ClientSchema);

这是我的路线:

router.post('/create', passVerify, async (req, res) => {
  try {
    const random = nanoid(5);
    const id = random.toUpperCase();
    if (req.body.vehicles)
      var vehicles = toId('6200d870c6d4758d29a86bed, 620b45cacddc8898b8919f3d');
    const body = new Client({ ...req.body, id, vehicles });
    const client = await body.save();

    if (client)
      res.status(200).send({
        success: true,
        data: client,
      });
    else
      res.status(404).send({
        success: false,
        message: 'Something went wrong adding the client.',
      });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: error,
    });
  }
});

所以我想将许多车辆分配给用户,但不知道如何解决。我认为模式现在可以接受不止一种车辆,因为它有数组,但要添加我不知道。

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您可以使用 $push 和 $each 将多个数据推送到一个数组。 例如:

     Client.updateOne(
         { id: clientID },
         {$push: {vehicles: {$each: [value1, value2, value3, ...]},
         function(error, success){}
      )
    

    (查看文档:https://docs.mongodb.com/manual/reference/operator/update/push/

    【讨论】:

    • 谢谢,但在这种情况下,我不做更新,你能模拟一下我的情况吗
    • 当我尝试将 $put 和 $push 添加在一起时它不起作用
    • 您能分享您收到的错误消息吗?您是在创建新的客户端对象还是向现有对象插入新元素?
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2021-06-05
    • 2019-08-11
    • 2020-06-12
    • 2015-05-20
    • 2018-04-04
    相关资源
    最近更新 更多