我正在编写一个使用Mongoose的Node JS应用程序,当我运行GET时,mongoose无法返回结果。
这是我的代码:
routes / api.js(一些注释掉的部分是MongoClient,对我有用)
const express = require('express');
const router = express.Router(); //HTTP requests
const MongoClient = require('mongodb').MongoClient; //MongoClient object. No need to setup models for mongoose.
const ObjectID = require('mongodb').ObjectID;
var mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE_CREDENTIALS);
var Users = require('./models/user');
var config = require('./config');
// Connect
// const connection = (closure) => {
// return MongoClient.connect(config.database_credentials, (err, db) => {
// if (err) return console.log(err);
// closure(db);
// });
// };
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
// Response handling
let response = {
status: 200,
data: [],
message: null
};
//HTTP GET
// Get users
router.get('/users', (req, res) => {
// connection((db) => {
// db.collection('users')
// .find()
// .toArray()
// .then((users) => {
// //response.data = users;
// res.json(users);
// })
// .catch((err) => {
// sendError(err, res);
// });
// });
console.log(process.env.DATABASE_CREDENTIALS);
User.find(function(err, users) {
if (err)
sendError(err);
res.json(users);
});
});
路由/模型/ user.js的
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String,
location: String
});
module.exports = mongoose.model('User', UserSchema);
我的MongoDb托管在Mlab上。使用MongoClient时,我可以使用它。任何建议都表示赞赏。