I am working on a project using MERN stack that will allow users to create their own documentation website that is similar to the way https://stripe.com/docs is set up.I am very new to using MongoDB and not familiar with document-based databases. However, I have taken a shot at modeling the database like so:const mongoose = require('mongoose'); const { Schema } = mongoose; const articleSchema = new Schema({ type: { type: String, required: true, }, name: { type: String, unique: true, required: true, }, slug: { type: String, unique: true, required: true, }, }); const sectionSchema = new Schema({ name: { type: String, unique: true, required: true, }, children: [articleSchema], }); const projectSchema = new Schema({ name: { type: String, index: true, unique: true, required: true, }, sections: [sectionSchema], }); mongoose.model('Project', projectSchema); The problem is that I am not sure how to fit the validation into my model. I have read up on validators here https://mongoosejs.com/docs/validation.html#custom-validatorsHowever, I am not sure how to make it so that no two articles (among all sections) can have the same name or slug. The best I have done is putting a ton of logic in my routes that looks through the document and checks for this before saving. I don't like it that way and I am beginning to think MongoDB is overcomplicating a very easy solution.Here is the code to update an article from my routes:// POST content router.post('/new', auth.required, async (req, res) => { const { body: { article } } = req; if (article) { try { // Query project const project = await Project.findOne({ name: 'MyProject' }); // Make changes to project // Find a section by name let section = project.sections.find(element => element.name === article.section); if (!section) { // If there is no section found, create one const index = project.sections.push({ _id: new mongoose.Types.ObjectId(), name: article.section, children: [], }); section = project.sections[index - 1]; } // Create child element for section const child = { _id: new mongoose.Types.ObjectId(), type: 'article', name: article.name, slug: article.slug, }; section.children.push(child); // Update in database try { await Project.findOneAndUpdate({ name: 'MyProject' }, project, { new: true }); } catch (err) { return res.status(400).json({ errors: { project: 'Unable to update project', err: err.message, }, }); } // S3 Upload const params = { Bucket: '#############', Key: `${child._id}.md`, Body: article.content.data, }; try { s3.upload(params, (err) => { if (err) throw err; }); } catch (err) { return res.status(400).json({ errors: { s3: 'Unable to save file', err: err.message, }, }); } return res.send(article.content); } catch (err) { return res.json({ errors: { section: 'Unable to create new article', }, }); } } return res.status(400).json({ errors: { article: 'Invalid article object', }, }); }); Can anyone provide help?
Submitted February 02, 2019 at 09:49PM by devaent1316
No comments:
Post a Comment