11const mongoose = require ( 'mongoose' )
2- const { Question } = require ( '../models/questionModel' )
2+ const { Question, Solution } = require ( '../models/questionModel' )
33const seedData = require ( '../data/seed.json' )
4+ const seedSolutions = require ( '../data/seed-solutions.json' )
45
56const connectDB = async ( ) => {
67 try {
@@ -13,6 +14,53 @@ const connectDB = async () => {
1314 const toInsert = seedData . map ( s => ( { ...s , status : 'Active' } ) )
1415 await Question . insertMany ( toInsert )
1516 console . log ( `Seeded ${ seedData . length } questions` )
17+ // sseed solutions that map to the seeded questions.
18+ try {
19+ const solCount = await Solution . countDocuments ( )
20+ if ( solCount === 0 ) {
21+ console . log ( 'No solutions found, seeding sample solutions...' )
22+
23+ const qDocs = await Question . find ( { } , 'questionID title' ) . lean ( )
24+ const titleToQID = { }
25+ qDocs . forEach ( q => { if ( q && q . title ) titleToQID [ q . title ] = q . questionID } )
26+
27+ const toInsert = seedSolutions . map ( s => {
28+ let mappedQID = s . questionID
29+ if ( ! mappedQID && s . questionTitle ) mappedQID = titleToQID [ s . questionTitle ]
30+ if ( ! mappedQID ) return null
31+ return {
32+ questionID : mappedQID ,
33+ title : s . title || `${ s . questionTitle || mappedQID } - solution` ,
34+ difficulty : s . difficulty || null ,
35+ topic : s . topic || null ,
36+ language : s . language || 'JavaScript' ,
37+ code : s . code || '' ,
38+ explanation : s . explanation || '' ,
39+ timeComplexity : s . timeComplexity || null ,
40+ spaceComplexity : s . spaceComplexity || null ,
41+ mediaLink : s . mediaLink || null ,
42+ status : s . status || 'Active'
43+ }
44+ } ) . filter ( Boolean )
45+
46+ if ( toInsert . length === 0 ) {
47+ console . log ( 'No seed solutions matched seeded questions, skipping solution auto-seed' )
48+ } else {
49+ try {
50+ const inserted = await Solution . insertMany ( toInsert , { ordered : false } )
51+ console . log ( `Seeded ${ Array . isArray ( inserted ) ? inserted . length : ( inserted && inserted . insertedCount ) || 0 } solutions` )
52+ } catch ( bulkErr ) {
53+ console . warn ( 'Some errors occurred while inserting solution seeds:' , bulkErr && bulkErr . message ? bulkErr . message : bulkErr )
54+ const finalCount = await Solution . countDocuments ( )
55+ console . log ( `Database now contains ${ finalCount } solutions` )
56+ }
57+ }
58+ } else {
59+ console . log ( `Database already contains ${ solCount } solutions, skipping auto-seed for solutions` )
60+ }
61+ } catch ( err ) {
62+ console . error ( 'Error while auto-seeding solutions:' , err )
63+ }
1664 } else {
1765 console . log ( `Database contains ${ questionCount } questions` )
1866 }
0 commit comments