2016-05-08 3 views
0

Итак, я пишу приложение календаря с помощью Node.JS и MongoDB. Но у меня возникли проблемы с добавлением информации из базы данных в текущий календарь.Как я могу получить доступ и ввести даты в мою базу данных? Node.JS & MongoDB

Здесь ошибка я получаю при попытке загрузить LocalHost:3000/init

TypeError: Cannot read property 'insert' of undefined at /home/patrick/Desktop/Javascript/CalandarApp/server.js:30:13 at Layer.handle [as handle_request] (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/layer.js:95:5) at next (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/route.js:131:13) at Route.dispatch (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/layer.js:95:5) at /home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/index.js:277:22 at Function.process_params (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/index.js:330:12) at next (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/index.js:271:10) at jsonParser (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/body-parser/lib/types/json.js:100:40) at Layer.handle [as handle_request] (/home/patrick/Desktop/Javascript/CalandarApp/node_modules/express/lib/router/layer.js:95:5)

Вот Javascript:

var express = require('express'); 
var bodyParser = require('body-parser'); 
var path = require('path'); 

//Connect to MongoDB 
var mongoskin = require('mongoskin'); 
var db = require('mongodb'); 
mongoskin.db("mongodb://localhost:3000/testDB", {w: 0}); 

//Creates Express Application 
var app = express(); 
app.use(express.static('public')); 


//is necessary for parsing POST request 
app.use(bodyParser.urlencoded({ 
    extended: true 
})); 
app.use(bodyParser.json()); 

console.log('Express server started on port 3000'); 

app.get('/init', function(req, res){ 
    db.event.insert({ 
     text:"Test Event A", 
     start_date: new Date(2016,5,1), 
     end_date: new Date(2016,5,5) 
    }); 
    db.event.insert({ 
     text:"Test Event B", 
     start_date: new Date(2016,5,3), 
     end_date: new Date(2016,5,8), 
     color: "#DD8616" 
    }); 

    res.send("Test Events were added to the Database") 
}); 


app.get('/data', function(req, res){ 
    db.event.find().toArray(function(err, data){ 
     //set id property for all records 
     for (var i = 0; i < data.length; i++) 
      data[i].id = data[i]._id; 

     //output response 
     res.send(data); 
    }); 
}); 

app.listen(3000); 
+0

Я не думаю, что вы правильно настройте коллекцию. Не должно быть что-то вроде 'db.collection ('event'). Insert()'. Также кажется, что вы используете '.get' для маршрута' .post'. Если вы вставляете информацию в базу данных, вам нужно использовать '.post' не' .get'. –

ответ

0

Вы получаете Cannot read property 'insert' of undefined, потому что db.event не определено. Вы должны использовать db.bind('COLLECTION_NAME'), чтобы связать события mongoskin с названием коллекции.

Кроме того, db должен быть создан с использованием монгоскина, и вам не нужно require('mongodb').

Ваш код может начать с этого:

// load mongoskin module 
var mongo = require('mongoskin'); 

// connect to local mongo database 
var db = mongo.db('127.0.0.1:27017/test'); 

// bind db.event to db.collection('event') so you can use db.event.insert 
db.bind('event'); 

// rest of tour code here 
0

Вот код вставки:

var Db = require('mongodb').Db; 
var Connection = require('mongodb').Connection; 
var Server = require('mongodb').Server; 
var db = new Db(dbName, new Server(host, port), {safe: true}); 
db.open(function (err, db) { 
    if (err) { 
     return callback(err); 
    } 
    db.collection('collectionName', function (err, collection) { 
     if (err) { 
     mongodb.close(); 
     return callback(err); 
     } 
     collection.insert(post, { 
     safe: true 
     }, function (err) { 
     mongodb.close(); 
     if (err) { 
      return callback(err); 
     } 
     callback(null); 
     }); 
    }); 
    }); 

Вот код доступа:

db.open(function(err, db) { 
    if(err) { 
     return callback(err); 
    } 
    db.collection('collectionName', function(err, collection) { 
     if(err) { 
     mongodb.close(); 
     return callback(err); 
     } 
     collection.findOne({ 
     query Condition 
     }, function(err, result) { 
     db.close(); 
     if(err) { 
      return callback(err); 
     } 
     callback(null, result); 
     }) 
    }); 
    }); 
Смежные вопросы