我在数据库 test
中有大量 300 个question
对象。我可以通过 MongoDB 的交互式 shell 轻松地与这个集合进行交互;但是,当我尝试在 express.js 应用程序中通过 Mongoose 获取集合时,我得到一个空数组。
我的问题是,我怎样才能访问这个已经存在的数据集,而不是在 express 中重新创建它?这是一些代码:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
mongoose.model('question', new Schema({ url: String, text: String, id: Number }));
var questions = mongoose.model('question');
questions.find({}, function(err, data) { console.log(err, data, data.length); });
这个输出:
null [] 0
最佳答案
Mongoose 添加了在架构下指定集合名称的功能,或者在声明模型时作为第三个参数。否则它将使用您映射到模型的名称给出的复数版本。
尝试以下类似的方法,无论是模式映射:
new Schema({ url: String, text: String, id: Number},
{ collection : 'question' }); // collection name
或模型映射:
mongoose.model('Question',
new Schema({ url: String, text: String, id: Number}),
'question'); // collection name
https://stackoverflow.com/questions/5794834/