如何使用 Mongoose 访问预先存在的集合? [英] How to access a preexisting collection with Mongoose?

查看:33
本文介绍了如何使用 Mongoose 访问预先存在的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库 test 中有 300 个 question 对象的大量集合.我可以通过 MongoDB 的交互式 shell 轻松地与这个集合进行交互;但是,当我尝试在 express.js 应用程序中通过 Mongoose 获取集合时,我得到一个空数组.

I have a large collection of 300 question objects in a database test. I can interact with this collection easily through MongoDB's interactive shell; however, when I try to get the collection through Mongoose in an express.js application I get an empty array.

我的问题是,如何访问这个已经存在的数据集而不是在 express 中重新创建它?这是一些代码:

My question is, how can I access this already existing dataset instead of recreating it in express? Here's some code:

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 添加了在模式下指定集合名称的功能,或者在声明模型时作为第三个参数.否则,它将使用您映射到模型的名称给出的复数版本.

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

尝试类似以下的操作,或者模式映射:

Try something like the following, either schema-mapped:

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

这篇关于如何使用 Mongoose 访问预先存在的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆