这是我的server.js。
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
CohortController =require('./CohortController');
var MongoURL='mongodb://username:password@ds037395.mongolab.com:37395/abc';
mongoose.connect(MongoURL,function (error) {
if (error)
console.error(error);
else
console.log('mongo connected');
});
app.use(bodyParser());
app.get('/api/cohorts',CohortController.list);
app.post('/api/cohorts',CohortController.create);
app.listen(3000,function(){
console.log('Listening...');
})
和我的CohortController.js
var mongoose=require('mongoose');
var Cohort=mongoose.model('Cohorts',new Schema({
id:Number,
name:String
}));
module.exports.create=function(req,res){
var cohort=new Cohort(req.body);
cohort.save(function(err,result){
res.json(result);
});
}
module.exports.list=
function(req,res){
Cohort.find({},function(err,results){
res.json(results);
});
}
当我运行节点服务器并使用URL
时本地主机:3000 / API /组群
我收到空JSON,即[]
但是当我将它与本地mongodb实例连接时,我得到了正确的JSON。
答案 0 :(得分:0)
尝试createConnection:
//Connect
var db = mongoose.createConnection(MongoURL);
db.on('error', console.error.bind(console, 'connection error:'));
//Once connected do actions
db.once('open', function callback () {
console.log('Connected to DB: '+MongoURL);
});
添加类别sshcema或您想要的任何架构:
var category = new Schema({
name : String,
quantity : Number
});
db.categories = db.model('categories', category)
答案 1 :(得分:0)
在架构中添加集合。
var schema = new Schema({
id:Number,
name:String
}, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)