我想将节点服务器连接到mongo并且有我的代码:
var http = require("http");
var url = require("url");
var Router = require('node-simple-router');
var router = Router();
var qs = require('querystring');
var mongoose = require('mongoose');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// mongo connection and use
mongoose.connect('mongodb://localhost/jobs');
var db = mongoose.connection;
db.on('error', function() {console.log("error")});
db.once('open', function () {
console.log("connected!");
// init the schema
var jobSchema = mongoose.Schema({ bName: String , phone :Number ,location:[{longitude:Number,latitude:Number}],Email:String,field:String,exp:String});
jobSchema.methods.printDetails = function() {
var str = "id=" + this.id + " name="+this.name;
console.log(str);
};
var job = mongoose.model('jobs',jobSchema);
//adding a jobs for testing :
var testJob = new job ({bName: 'Microsoft' , phone :'035588319' ,location:[{longitude:'7.8',latitude:'7.8'}],Email:'microsoft@gmail.com' ,field:'QA',exp:'0-2'});
testJob.save(function(error,prod) {
if(error) {
console.log(error);
}
else {
console.log("a job was saved to mongodb");
//testJob.printDetails();
}
)};
function start(route) {
function onRequest(request, response) {
var path = url.parse(request.url).pathname;
console.log("Request for " +path+ "received.");
route(path);
if(request.method==='GET')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
console.log(request.body);
response.end("res");
}
else if(request.method === 'POST')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
//var userString = JSON.stringify(body);
response.end("POST REQUEST");
}
else if (request.method==='PUT')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
response.end("put request");
}
else if(request.method==='DELETE')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
response.end("delete request");
}
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
由于第79行的语法错误,我没有启动我的服务器,但我只有78行。 语法错误意外结束输入:});如果这是在mongo和节点web服务器之间进行连接的正确方法,那么任何人都可以告诉我。
答案 0 :(得分:1)
当你致电db.once("open", function () {
时,你永远不会关闭那个paren和大括号。
我认为你需要在});
声明之后testJob
。那也应该是})
而不是)}
。