mongoose怎么取到某个collection的数据?
发布于 8 年前 作者 Orange-C 7078 次浏览 来自 问答

题主初学node+mongodb,使用了mongoose模块,在取数据时出现了问题,我想获得数据库中某个collection的所有数据,但是取得的是空数组

//数据库连接和部分路由代码,不相关的部分都省略了
var Comment = require('./models/comment');
mongoose.connect('mongodb://localhost:27017/nodetest')
app.get('/api/comments',function(req, res){
	Comment.fetch(function (err,data) {
		if(err){
			console.log(err);
		}
		res.send(data);
	})
})


//model代码,这两段代码在不同的文件中
var mongoose = require('mongoose');
var CommentSchema = new mongoose.Schema({
	author: String,
	text: String
});
CommentSchema.statics = {
	fetch: function(cb){
		return this
			.find({})
			.exec(cb)
	}
	// findById: function(id,cb){
	//     return this
	//         .findOne({_id: id})
	//         .exec(cb)
	// }
}
var Comment = mongoose.model('Comment',CommentSchema);
module.exports = Comment;

数据库名字为nodetest,其中有一个叫做comment的collection,里面放了若干数据,数据属性为author和text

6 回复
Comment.fetch(function (err,data) {

这个 .fetch 是啥?文档里没有。

@coderfox 是我定义的静态方法,下面代码有

@Orange-C 抱歉抱歉,没看到。

Mongoose 默认的 Model 对应 Collection 名字是带 s 的,也就是你这个 Model 对应的是 comments 而不是 comment

如果需要指定 Collection 的名字需要带参数。

@coderfox 原来是这样啊……多谢多谢,那如果指定collection名字应该怎么写呢?

@Orange-C

let userSchema: mongoose.Schema = new mongoose.Schema({
  username: { type: String, index: { unique: true } },
  password: String
}, { collection: "users" });
回到顶部