Reputation: 101
I have a route that is inserting an array of documents into a collection. I also want to capture the _is of the document into a user schema but I'm getting a CastError, how do I resolve this. here is my code:
the error:
(node:23088) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "
{
_id: 6032c1df6761405a308736f0,
name: ' test1',
surname: 'test',
email: '[email protected]',
phone: '0915461',
__v: 0
},
{
_id: 6032c1df6761405a308736f1,
name: 'jane',
surname: 'doe',
email: '[email protected]',
phone: '12345678',
__v: 0
}
]" at path "references"
route:
app.post('/register_two/:id/references', async (req, res) => {
const staff = await Worker.findById(req.params.id);
const reference = await Reference.insertMany(req.body.references);
await staff.references.push(reference); <<--- Error when i try to push document IDs
});
my reference schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ReferenceSchema = Schema({
name: String,
surname: String,
email: String,
phone: String
});
module.exports = mongoose.model('Reference', ReferenceSchema);
my worker schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const WorkerSchema = new Schema({
name: String,
surname: String,
role: String,
nationality: String,
gender: String,
dateofbirth: Date,
contactnumber: String,
email: String,
address: String,
region: String,
righttowork: String,
righttoworkproof: String,
ninumber: String,
references: [
{
type: Schema.Types.ObjectId,
ref: 'Reference'
}
],
date: Date
});
module.exports = mongoose.model('Worker', WorkerSchema);
edit: fixed worker schema
Upvotes: 0
Views: 273
Reputation: 7905
You should run the insertMany
command with the rawResult
option set to true
const reference = await Reference.insertMany(req.body.references, {rawResult: true});
This way you will get the raw result from the MongoDB driver back into reference
. That result will be an object that will contain this prop:
...
...
insertedIds: { '0': 6032ce0ed7fd8568aef0d0cd, '1': 6032ce0ed7fd8568aef0d0ce, ... }
...
insertedIds
is what you need, but you need them in the form of an array. So here is what your code should look like:
const reference = await Reference.insertMany(req.body.references, {rawResult: true});
await staff.references.push(...Object.values(reference.insertedIds));
Credit to Emil C., who pointed out that by pushing an array we would simply be creating array of arrays inside the reference
path. Spreading is the answer.
Upvotes: 1
Reputation: 101
I managed to solve it using the spread operator, all I did was change:
await staff.references.push(reference);
to
await staff.references.push(...reference);
Upvotes: 1