'Mongodb and Mongoose putting many id for relationship
So I have Client and Vehicle model, so what I want to do is add many Vehicles to the Client (many ids) but I don't know how to do it, it works fine with one but not with two. I tried some anwsers with array but seems is not working.
Here is the route:
router.post('/create', passVerify, async (req, res) => {
try {
var vehicles = null;
var orders = null;
const body = req.body;
if (req.body.vehicles) vehicles = toId(req.body.vehicles);
if (req.body.vehicles) orders = toId(req.body.orders);
const save = new Client({ ...body, vehicles, orders });
const client = await save.save();
if (client)
res.status(200).send({
success: true,
data: client,
});
else
res.status(404).send({
success: false,
message: 'Something went wrong while adding the client to database.',
});
} catch (error) {
res.status(500).send({
success: false,
message: error,
});
console.log(error);
}
});
And here is the part of the model:
vehicles: [
{
type: Types.ObjectId,
ref: 'vehicle',
},
],
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|