Skip to content

Instantly share code, notes, and snippets.

Created February 7, 2018 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/90e14b3f809ebfce8ee483f1f94e8cfa to your computer and use it in GitHub Desktop.
Save anonymous/90e14b3f809ebfce8ee483f1f94e8cfa to your computer and use it in GitHub Desktop.
const express = require('express');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//Mongo connection
mongoose.connect('mongodb://localhost/webapp',(error)=>{
if(error) throw error;
console.log('Mongodb Connected');
});
//Load Schema
require('./models/Idea');
const Idea = mongoose.model('ideas');
//BodyParser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//Handlebars Middleware
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.get('/', (req,res)=>{
const title = 'welcome';
res.render('index',{
title :title
});
});
app.get('/about',(req,res)=>{
res.render('about');
});
//Add Ideas
app.get('/ideas/add', (req, res) => {
res.render('ideas/add');
});
//Process Form
app.post('/ideas',(req,res)=>{
let errors = [];
if(!req.body.title){
errors.push({text:'Please add a title'});
}
if(!req.body.details){
errors.push({text:'Please add some Details'});
}
if(errors.length > 0){
res.render('ideas/add',{
errors : errors,
title: req.body.title,
details: req.body.details
});
}else{
res.send('Successful');
}
});
const port = 5000;
app.listen(port,() => {
console.log(`Server is running on port ${port}`);
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create Schema
const IdeaSchema = new Schema({
title:{
type: String,
required: true
},
details:{
type: String,
required: true
},
date:{
type:Date,
default: Date.now
}
});
mongoose.model('ideas',IdeaSchema);
@lineus
Copy link

lineus commented Feb 7, 2018

I would change the last line of Idea.js to:

module.exports = mongoose.model('ideas', IdeaSchema)

and lines 18/19 of app.js to:

const Idea = require('./models/Idea')

if you expect mongoose to add the collection to the db, you'll need to create an instance and save it like this:

const myIdea = new Idea({
  title: 'tear down the walls',
  details: 'build friendships not barriers.',
})
myIdea.save(function(err, result) {
  if (err) { return console.error(err) }
  console.log(result) // this should print out the newly saved idea
})

@lineus
Copy link

lineus commented Feb 7, 2018

alternatively if you're dealing with an existing db called ideas and you want display them
after you've required the Idea module:

Idea.find({}, function (err, result){
  if (err) { return console.error(err) }
  console.log(result)
})

@lineus
Copy link

lineus commented Feb 7, 2018

here is why I suggested the changes to your module:

$: cat reqTest.js 
const idea = require('./idea')

console.log(idea)

$: cat idea.js 
const mongoose = require('mongoose')
const Schema = mongoose.Schema

//Create Schema
const IdeaSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  details: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now

  }
})

mongoose.model('ideas', IdeaSchema)

$: node reqTest.js 
{} // this is not what you should expect when requiring a module
 

after making the suggested change to idea.js:

$: cat reqTest.js 
const idea = require('./idea')

console.log(idea)

$: cat idea.js 
const mongoose = require('mongoose')
const Schema = mongoose.Schema

// Create Schema
const IdeaSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  details: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now

  }
})

module.exports = mongoose.model('ideas', IdeaSchema)

$: node reqTest.js 
{ [Function: model]
  hooks: 
   Kareem {
     _pres: { save: [Array], remove: [Array] },
     _posts: { init: [Array], save: [Array] } },
  base: 
   Mongoose {
     connections: [ [NativeConnection] ],
     models: { ideas: [Circular] },
     modelSchemas: { ideas: [Schema] },
     options: { pluralization: true },
     _pluralize: [Function: pluralize],
     plugins: [ [Array], [Array], [Array], [Array] ] },
  modelName: 'ideas',
  model: [Function: model],
  db: 
   NativeConnection {
     base: 
      Mongoose {
        connections: [Array],
        models: [Object],
        modelSchemas: [Object],
        options: [Object],
        _pluralize: [Function: pluralize],
        plugins: [Array] },
     collections: { ideas: [NativeCollection] },
     models: { ideas: [Circular] },
     config: { autoIndex: true },
     replica: false,
     hosts: null,
     host: null,
     port: null,
     user: null,
     pass: null,
     name: null,
     options: null,
     otherDbs: [],
     states: 
      { '0': 'disconnected',
        '1': 'connected',
        '2': 'connecting',
        '3': 'disconnecting',
        '99': 'uninitialized',
        disconnected: 0,
        connected: 1,
        connecting: 2,
        disconnecting: 3,
        uninitialized: 99 },
     _readyState: 0,
     _closeCalled: false,
     _hasOpened: false,
     _listening: false },
  discriminators: undefined,
  '$appliedMethods': true,
  '$appliedHooks': true,
  schema: 
   Schema {
     obj: { title: [Object], details: [Object], date: [Object] },
     paths: 
      { title: [SchemaString],
        details: [SchemaString],
        date: [SchemaDate],
        _id: [ObjectId],
        __v: [SchemaNumber] },
     aliases: {},
     subpaths: {},
     virtuals: { id: [VirtualType] },
     singleNestedPaths: {},
     nested: {},
     inherits: {},
     callQueue: [],
     _indexes: [],
     methods: {},
     statics: {},
     tree: 
      { title: [Object],
        details: [Object],
        date: [Object],
        _id: [Object],
        __v: [Function: Number],
        id: [VirtualType] },
     query: {},
     childSchemas: [],
     plugins: [ [Object], [Object], [Object], [Object], [Object] ],
     s: { hooks: [Kareem] },
     _userProvidedOptions: undefined,
     options: 
      { typeKey: 'type',
        id: true,
        noVirtualId: false,
        _id: true,
        noId: false,
        validateBeforeSave: true,
        read: null,
        shardKey: null,
        autoIndex: null,
        minimize: true,
        discriminatorKey: '__t',
        versionKey: '__v',
        capped: false,
        bufferCommands: true,
        strict: true,
        pluralization: true },
     '$globalPluginsApplied': true },
  collection: 
   NativeCollection {
     collection: null,
     opts: 
      { bufferCommands: true,
        capped: false,
        '$wasForceClosed': undefined },
     name: 'ideas',
     collectionName: 'ideas',
     conn: 
      NativeConnection {
        base: [Mongoose],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        hosts: null,
        host: null,
        port: null,
        user: null,
        pass: null,
        name: null,
        options: null,
        otherDbs: [],
        states: [Object],
        _readyState: 0,
        _closeCalled: false,
        _hasOpened: false,
        _listening: false },
     queue: [],
     buffer: true,
     emitter: 
      EventEmitter {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined } },
  Query: 
   { [Function]
     base: 
      Query {
        toConstructor: [Function: toConstructor],
        setOptions: [Function],
        collection: [Function: collection],
        '$where': [Function],
        where: [Function],
        equals: [Function: equals],
        eq: [Function: eq],
        or: [Function: or],
        nor: [Function: nor],
        and: [Function: and],
        gt: [Function],
        gte: [Function],
        lt: [Function],
        lte: [Function],
        ne: [Function],
        in: [Function],
        nin: [Function],
        all: [Function],
        regex: [Function],
        size: [Function],
        maxDistance: [Function],
        minDistance: [Function],
        mod: [Function],
        exists: [Function],
        elemMatch: [Function],
        within: [Function: within],
        box: [Function],
        polygon: [Function],
        circle: [Function],
        near: [Function: near],
        intersects: [Function: intersects],
        geometry: [Function: geometry],
        select: [Function: select],
        slice: [Function],
        sort: [Function],
        limit: [Function],
        skip: [Function],
        maxScan: [Function],
        batchSize: [Function],
        comment: [Function],
        maxTime: [Function],
        snapshot: [Function],
        hint: [Function],
        slaveOk: [Function],
        read: [Function],
        tailable: [Function],
        merge: [Function],
        find: [Function],
        cursor: [Function: cursor],
        findOne: [Function],
        count: [Function],
        distinct: [Function],
        update: [Function: update],
        updateMany: [Function: updateMany],
        updateOne: [Function: updateOne],
        replaceOne: [Function: replaceOne],
        remove: [Function],
        deleteOne: [Function],
        deleteMany: [Function],
        findOneAndUpdate: [Function],
        findOneAndRemove: [Function],
        _findAndModify: [Function],
        _wrapCallback: [Function],
        setTraceFunction: [Function],
        exec: [Function: exec],
        thunk: [Function],
        then: [Function],
        stream: [Function],
        selected: [Function: selected],
        selectedInclusively: [Function: selectedInclusively],
        selectedExclusively: [Function: selectedExclusively],
        _mergeUpdate: [Function],
        _optionsForExec: [Function],
        _fieldsForExec: [Function],
        _updateForExec: [Function],
        _ensurePath: [Function],
        _validate: [Function] } },
  '$__insertMany': [Function],
  '$init': Promise { <pending>, catch: [Function] } }
$: 

you can see, by setting the default export of the module to the model, your require should provide you with a model to work with.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment