2017-11-15 1 views
0

MEAN 스택을 사용하여 프로젝트에 API를 빌드하고 있습니다. 나는 mongodb를 설정하고 테스트를 위해 작은 컬렉션을 삽입했습니다. 그런 다음 API로 간단한 노드 응용 프로그램을 만들었습니다. mongo에서 스키마를 정의하는 모델을 작성했습니다. 그러나 그것은 끝점을 호출 할 때 null을 출력하고 컬렉션 안의 문서에 액세스하지 않습니다. 나는 일반적인 의미의 초심자이고 노드와 몽고를 사용한 나의 최초의 응용 프로그램이다. 나는 필자가 지금까지 무슨 짓을 붙여 넣은 아래 : 이미 몇 로그에 던져 필자을 볼 수 있듯이Node.js 응용 프로그램이 JSON을 반환하지 않습니까?

var express = require("express"); 
//need an object to represent express 
var app = express(); 
var bodyParser = require("body-parser"); 
var mongoose = require("mongoose"); 

//Connect to mongoose. 
mongoose.connect("mongodb://localhost/finalyearproject", { 
useMongoClient: true }); 
//db object 
var db = mongoose.connection; 

Victims = require("./models/victims"); 

//here we handle requests 
//starts with get request 
app.get("/", function(req, res) { 
res.send("First line!!"); 
}); 

app.get("/api/victims", function(req,res){ 
    Victims.getVictims(function(err, victims){ 
    if(err) { 
     throw err; 
    } 
    res.json(victims); 
    console.log(err); 
    console.log(victims.location); 
}); 
}); 

app.listen(8001); 
console.log("We are live on port 8001...."); 

이를 디버깅 할 수 있습니다. 그리고 내 모델에 해당하는 코드가 있습니다.

var mongoose = require("mongoose"); 

//Victims Schema 
var victimsSchema = mongoose.Schema({ 
    age : { 
    type : Number, 
    default : 0, 
    required : true 
    }, 
    gender : { 
    type : String, 
    required : true 
    }, 
location : { 
    type : String, 
    required : true 
    }, 
    type_of_crime : { 
    type : String, 
    required : true 
    } 
}); 

var Victims = module.exports = mongoose.model("Victims", victimsSchema); 

//get Victims 
module.exports.getVictims = function(callback){ 
    console.log(callback); 
    Victims.find(callback); 
}; 

내 출력 반환이 :

We are live on port 8001.... 
[Function] 
null 
undefined 

그것은 응용 프로그램은 아직 초기 단계부터 매우 간단 보이지만, 내가 어떻게 문제를 해결하는 방법 아무 생각이 없다?! 누군가 노드를 가지고 꽤 새로운 것을 말했기 때문에 누군가 이걸 도와 주실 수 있습니까?

+1

'피해자'를 기록하면 도움이 될 것입니다 ... – jcaron

+0

나는 이미 가지고 있으며 그 정의가 없다고 말합니다! –

답변

0

// Express에는 미들웨어 기능이 있습니다. 들어오는 요청을 JSON 페이로드로 구문 분석하고 body-parser를 기반으로합니다. 당신은 또한 mongoose statics

사용을 고려 할 수 있습니다 하나

app.use(bodyParser.urlencoded({extended: true})); 
app.use(bodyParser.json()); 
0

이, 내가 find 방법은 첫 번째 매개 변수 다음 콜백으로 condition/query을 필요로 믿고 추가합니다. 어쩌면

// get all the users 
User.find({}, function(err, users) { 
    if (err) throw err; 

    // object of all the users 
    console.log(users); 
}); 

또는 당신이 ID로 검색 할 :

// get a user with ID of 1 
User.findById(1, function(err, user) { 
    if (err) throw err; 

    // show the one user 
    console.log(user); 
}); 

는 희망이

0

당신은 예를 들어, "콜백"대신 객체를 사용할 필요가 해결책을 찾도록 도와 주신 모든 분들께 감사드립니다. 문제가있는 곳과 내 db가 localhost를 통해 moongose에게 말하려고하는 곳을 발견했습니다. 나는 실제 데이터베이스의 이름보다는 내 응용 프로그램의 이름을 지정했습니다. 이름을 바꾸면 내가 원하는 결과를 얻었습니다.

0

을하는 데 도움이

victimsSchema.statics.getVictims = function(callback) { 
    return this.find({}, callback); 
}; 
관련 문제