How can I validate an array of mongoDB object Ids?

Viewed 174

I am building a REST API record collection using Node, Express, and MongoDB where the user can add artists, add records, add records to artists, and add artists to records.

Here is my "SUBMIT RECORD" post request, where "artists" is an array of object ids that reference already created artist objects. However, right now, you can add a record with invalid artist IDs (i.e. IDs for artists that don't exist).

Is there a way to validate each element in the array of artist IDs before saving it (i.e. validating each ID belongs to an artist object)?

// TODO: VALIDATE ALL ARTISTS EXIST BEFORE ADDING RECORD
router.post('/records', async (req, res) => {
    let record = new Record({
        name: req.body.name,
        releaseDate: req.body.releaseDate,
        link: req.body.link,
        artists: req.body.artists
    });
    try {
        const savedRecord = await record.save();

        // UPDATE ARTIST
         const artist = record.artists.map(element => Artist.updateOne({_id: element}, {$push: {records: record}}));
         await Promise.all(artist);

        res.status(200).json(savedRecord);
    } catch (err) {
        res.status(500).json({message: err.message});
    }
});
0 Answers
Related