Node.js 如何使用特定集合Mongoose Express Mongodb(平均堆栈)
我从MEAN STACK开始,所以我接受了他们的项目(关于发布文章),我试图对其进行成本分析,以便获得所有流的列表,我可以使用angularjs进行过滤,也可以通过id进行过滤。 我遵循他们为文章所做的相同操作,创建与流相关的JS文件(流是我的对象)。因此,我有一个名为flows的集合,我将它导入到MEAN STACK(db==MEAN dev)使用的同一个db中,并尝试了以下代码:Node.js 如何使用特定集合Mongoose Express Mongodb(平均堆栈),node.js,mongodb,express,mongoose,mean-stack,Node.js,Mongodb,Express,Mongoose,Mean Stack,我从MEAN STACK开始,所以我接受了他们的项目(关于发布文章),我试图对其进行成本分析,以便获得所有流的列表,我可以使用angularjs进行过滤,也可以通过id进行过滤。 我遵循他们为文章所做的相同操作,创建与流相关的JS文件(流是我的对象)。因此,我有一个名为flows的集合,我将它导入到MEAN STACK(db==MEAN dev)使用的同一个db中,并尝试了以下代码: // myApp/serves/models/flow.js 'use strict'; var mongoo
// myApp/serves/models/flow.js
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// Flow Schema
var FlowSchema = new Schema({
_id: {
type: Number,
default: ''
},
name: {
type: String,
default: '',
trim: true
},
Clients: {
type: Array,
default: '',
trim: true
},
DP Prot: {
type: String,
default: ''
}
/* And 15 others attributes...*/
});
/** Statics */
FlowSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).exec(cb);
};
// Define the collection
mongoose.model('Flow', FlowSchema);
控制器代码:
// servers/controllers/flows.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Flow = mongoose.model('Flow'),
_ = require('lodash');
/**
* Find flow by id
*/
exports.flow = function(req, res, next, id) {
Flow.load(id, function(err, flow) {
if (err) return next(err);
if (!flow) return next(new Error('Failed to load flow ' + id));
req.flow = flow;
next();
});
};
/**
* New code count Flows
*/
exports.compte = function(req, res) {
var c;
flow.count({}, function(err, count) {
if (err) return next(err);
c = count;
res.jsonp (count);
});
};
/**
* Show Flow
*/
exports.show = function(req, res) {
res.jsonp(req.flow);
};
/**
* List of Flows
*/
exports.all = function(req, res) {
Flow.find().sort('-name').populate('name', 'application').exec(function(err, flows) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(flows);
}
});
};
我还添加了路线。。。但它不起作用,你认为我犯了一些错误吗?提前感谢您的帮助文档向您展示了如何: 创建架构时,可以显式选择集合:
// Flow Schema
var FlowSchema = new Schema({
/* attributes...*/
}, {
collection: 'my-collection'
});
或者,您可以稍后在创建的架构上进行设置:
// Flow Schema
var FlowSchema = new Schema({
/* attributes...*/
});
FlowSchema.set('collection', 'my-collection');
我相信这是在Mongoose 3.4中添加的,所以请检查您正在使用的Mongoose版本。有关强制使用集合名称的查询,请参阅本文:
其中,qux是您的集合,假设您连接到mongo connect中的正确db。Express中间件始终采用三个参数:req、res和next。流方法中的Id为“未定义”。您很可能会在req.params或req.body中找到它,具体取决于您如何实现路由。
var mySchema = new Schema({
foo: bar
}, { collection: qux });