This is the code :
async function create(data: any) {
try {
//Creates and order
let createdOrder = await model.create(data);
//Push into bike orders array the id of the newly created order
let bike = await bikeModel.findById(createdOrder._id);
bike?.orders.push(createdOrder._id);
} catch (error: any) {
console.log(`[${RESOURCE}:create] controller error:${error}`);
throw error;
}
}
This is the error I get:
Argument of type 'ObjectId' is not assignable to parameter of type '{ type: typeof mongoose.Types.ObjectId; ref: "Order"; }'.
Type 'ObjectId' is missing the following properties from type '{ type: typeof ObjectId; ref: "Order"; }': type, refts(2345)
And this is my model :
const bikeSchema = new mongoose.Schema({
name: String,
model: String,
color: String,
location: String,
rating: String,
available: String,
orders: [
{
type: mongoose.Types.ObjectId,
ref: 'Order',
},
],
});
I tried almost everything but it doesnt seem to let me do anything
The problem is that you are trying to push a single value onto an array of objects the correct. If look at your schema you will notice that your orders attribute is of type:
{ type: mongoose.Types.ObjectId, ref: 'Order' }[]
Hence what your code should look as follows:
async function create(data: any) {
try {
//Creates and order
let createdOrder = await model.create(data);
//Push into bike orders array the id of the newly created order
let bike = await bikeModel.findById(createdOrder._id);
bike?.orders.push({type: createdOrder._id, ref: 'order'});
} catch (error: any) {
console.log(`[${RESOURCE}:create] controller error:${error}`);
throw error;
}
}