BaherZ
BaherZ

Reputation: 69

Mongo database is not created using mongoose

I want to create a database with the schema created in my data.js file but the database doesn't get created

index.js:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path'); 
var expressValidator = require('express-validator');
var mongoose = require('mongoose');
var Data = require('./models/data');

mongoose.connect('mongodb://localhost:27017/data');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'mongodb connection 
error'));
db.once('open', () => console.log('mongodb connected'));

//app.use(expressValidator(customValidators));
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/',function(req,res){
    var d = new Data({optionName:"switchOnLights",optionValues:
                                             ["switchOnLights"]});
    d.save(err =>{console.error(err)});
    res.render('index');
});

app.post('/users/add',function(req,res){
   var text = req.body.text;
   var option = req.body.option; 
   db.Data.update(
    {optionName:option},
    {$addToSet:{optionValues:text}})
});

app.listen(3001,function(){
  console.log("server is running");
})

data.js (my model):

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var dataSchema = new Schema({
   optionName:String,
   optionValues:[{type:String}]
});
var Data = mongoose.model('Data',dataSchema);
module.exports = Data;

I also tried testing the database by adding a new document when accessing the homepage but it still didn't create the database

Upvotes: 0

Views: 1028

Answers (1)

kirecligol
kirecligol

Reputation: 875

You should first create an instance of model then save it to the database. Instead of

db.Data.update()

try the following code block:

var d = new Data({//columns});
d.save(err => {//handle errors});

for more information you can have a look at mongoos official docs

Upvotes: 1

Related Questions