新手加入Node.JS和Mongoose。
在Postman中,我可以使用'/movies/title/:movieTitle'
或'/movies/genre/:movieGenre'
来获得响应,但是不能使用'/access/:inputSearch'
来获得正确的查询(空数组)。
可以确定我的数据库没有问题(已经在Mongo中进行了测试)。
appModel.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var movies = new Schema({
MovieID: String,
Title: String,
Genres: String
});
var access = new Schema({
Address: String,
Timestamp: String,
Request: String
});
module.exports = mongoose.model('access', access);
module.exports = mongoose.model('movies', movies);
appRouter.js
'use strict';
module.exports = function(app) {
var mangoCollc = require('../controllers/appController');
app.route('/movies/title/:movieTitle').get(mangoCollc.search_all_movies_by_title);
app.route('/movies/genre/:movieGenre').get(mangoCollc.search_all_movies_by_genre);
app.route('/access/:inputSearch').get(mangoCollc.search_all_access);
};
appController.js
'use strict';
var mongoose = require('mongoose');
var movies = mongoose.model('movies');
var access = mongoose.model('access');
exports.search_all_access = function(req, res) {
access.find(
{Address: "127.0.0.1"},
function(err, ret) {
if (err)
res.send(err);
res.json(ret);
})
.limit(30);
};
exports.search_all_movies_by_title = function(req, res) {
movies.find(
{$or: [
{Title: { $regex: req.params.movieTitle }}
]},
function(err, ret) {
if (err)
res.send(err);
res.json(ret);
})
.sort({Title: 1})
.limit(20);
};
exports.search_all_movies_by_genre = function(req, res) {
movies.find(
{Genres: { $regex: req.params.movieGenre }},
function(err, ret) {
if (err)
res.send(err);
res.json(ret);
})
.sort({Title: 1})
.limit(20);
};
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
MangoWork = require('./api/models/appModel'), //created model loading here
bodyParser = require('body-parser');
// mongoose instance connection url connection :27017
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/info7250');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/appRoutes'); //importing route
routes(app); //register the route
app.listen(port);
console.log('server started on: ' + port);