用NodeJS编写我的第一个应用程序。我有一个带有两个模式的MongoDB" blurbs"和"用户"。我希望能够通过localhost / api / blurbs和localhost / api / users为这两者设置API。但是,这两个URL都会返回" blurbs"的信息。很感谢任何形式的帮助。这是我的代码:
/models/db.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Connect to the database
var dbURI = 'mongodb:/\/localhost/scuba-noodle';
mongoose.connect(dbURI);
// Creating the user schema
var UserSchema = new Schema({
"firstName": String,
"lastName": String,
"userId": String,
"avatar": Buffer,
"email": { type: String, unique: true },
"created": {type: Date, default: Date.now },
"loggedIn": Boolean,
"lastLogin": Date,
"noOfBlurbs": Number,
"blurbs": [null],
"votedOnBlurbs": [null],
"rating": Number
});
// Exporting the user schema
module.exports = mongoose.model('User', UserSchema);
// Creating the blurb schema
var BlurbSchema = new Schema ({
"author": String,
"submitted": Date,
"votes": Number,
"trunk": String,
"text": String
});
// Exporting the blurb schema
module.exports = mongoose.model('Blurb', BlurbSchema);
// Disconnect from the DB on App termination
process.on('SIGINT', function() {
mongoose.connection.close(function() {
console.log("Mongoose disconnected through app termination");
process.exit(0);
});
});
/routes/user.js:
var express = require('express'),
mongoose = require('mongoose'),
router = express.Router(),
User = require('../models/db');
router.use(function(req, res, next) {
console.log("Incoming request...");
next();
});
router.route('/')
// POST
.post(function(req, res){
var user = new User();
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.userName = req.body.userName;
user.avatar = req.body.avatar || null;
user.email = req.body.email;
user.created = Date.now();
user.loggedIn = false;
user.lastLogin = Date.now();
user.noOfBlurbs = 0;
user.blurbs = [null];
user.votedOnBlurbs = [null];
user.rating = 0;
user.save(function (err) {
if (err) { res.send(err); }
res.json({ message: "User created" });
});
})
// GET all
.get(function(req, res) {
User.find(function(err, users) {
if (err) { res.send(err); }
res.json(users);
});
});
router.route('/:user_id')
//GET by ID
.get(function(req, res) {
User.findById(req.params.user_id, function(err, user) {
if (err) { res.send(err); }
res.json(user);
});
})
//PUT by ID
.put(function(req, res) {
User.findById(req.params.user_id, function(err, user) {
if (err) { res.send(err); }
user.firstName = req.body.firstName || user.firstName;
user.lastName = req.body.lastName || user.lastName;
user.userName = req.body.userName || user.userName;
user.avatar = req.body.avatar || user.avatar;
user.email = req.body.email || user.email;
user.save(function(err, user) {
if (err) { res.send(err); }
res.json({ message: "User update" });
});
});
})
// DELETE by ID
.delete(function(req, res) {
User.remove({
_id: req.params.user_id
}, function(err, user) {
if (err) { res.send(err); }
res.json({ message: "Successfully Deleted" });
});
});
var userRouter = router;
module.exports = userRouter;
/routes/blurb.js:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var Blurb = require('../models/db');
router.use(function(req, res, next) {
console.log("Incoming request...");
next();
});
router.route('/')
// POST
.post(function(req, res) {
var blurb = new Blurb();
blurb.author = req.body.author || "Anonymous";
blurb.submitted = Date.now();
blurb.votes = 0;
blurb.trunk = req.body.trunk || "Unspecified";
blurb.text = req.body.text || "Empty";
blurb.save(function (err) {
if(err) { res.send("Save Error: " + err); }
res.json({ message: "Blurb Created" });
});
})
// GET all
.get(function(req, res) {
Blurb.find(function(err, blurbs) {
if (err) { res.send(err); }
res.json(blurbs);
});
});
router.route('/:blurb_id')
// GET by ID
.get(function(req, res) {
Blurb.findById(req.params.blurb_id, function(err, blurb) {
if (err) { res.send(err); }
res.json(blurb);
});
})
// PUT by ID
.put(function(req, res){
Blurb.findById(req.params.blurb_id, function(err, blurb){
if (err) { res.send(err); }
blurb.author = req.body.author || blurb.author;
blurb.submittee = Date.now();
blurb.votes = blurb.votes;
blurb.trunk = req.body.trunk || blurb.trunk;
blurb.text = req.body.text || blurb.text;
blurb.save(function(err) {
if (err) { res.send(err); }
res.json({ message: 'Blurb Updated' });
});
});
})
// DELETE by ID
.delete(function(req, res) {
Blurb.remove({
_id: req.params.blurb_id
}, function(err, blurb) {
if (err) { res.send(err); }
res.json({ message: 'Successfully Deleted' });
});
});
var blurbRouter = router;
module.exports = blurbRouter;
最后,server.js:
// Call packages
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
// Create the server
var app = express();
// Configure bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Setting the port
var port = process.env.PORT || 8080;
// Registering the routes
app.use('/api/blurbs', require('./routes/blurb'));
app.use('/api/users', require('./routes/user'));
// Starting the server
app.listen(port);
console.log('Nodejs Server Listening on port ' + port);
如果您有任何想法或建议,我真的很感激!
答案 0 :(得分:1)
原因是您正在覆盖module.exports
中的db.js
:
module.exports = mongoose.model('User', UserSchema);
// ...
module.exports = mongoose.model('Blurb', BlurbSchema);
因为后者是最后一个分配,db.js
将导出Blurb
模型。你可能应该做一些类似的事情:
exports.User = mongoose.model('User', UserSchema);
exports.Blurb = mongoose.model('Blurb', BlurbSchema);
并适当更改路径文件:
var User = require('../models/db').User;
和
var Blurb = require('../models/db').Blurb;