首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么在我的应用中看不到我的Mongodb集合?

为什么在我的应用中看不到我的Mongodb集合?
EN

Stack Overflow用户
提问于 2019-03-15 07:59:21
回答 1查看 35关注 0票数 -1

这对mongodb来说是全新的,但我认为肯定有一些非常基本的东西我没有理解。如果我运行shell并输入db.questions.count(),我会得到1,这是我在shell中创建的1。但如果我在我的应用程序中做同样的事情:

代码语言:javascript
复制
...
const MONGO_URL = 'mongodb://127.0.0.1:27017/';
const {MongoClient, ObjectId} = mongo;

const run = async () => {
  try {
    const db = await 
    MongoClient.connect(MONGO_URL);

    const Questions = db.questions; 
    console.log(Questions.count()); 
...

我得到了Cannot read property 'count' of undefined。为什么会这样呢?

值得注意的是,定义了db,并且URL与shell中的URL相同。另外,服务器启动得很好,所以我认为这意味着mongodb实例运行良好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-15 08:19:08

安装mongodb npm模块。它是NodeJs的官方MongoDB客户端。

代码语言:javascript
复制
// Create a Mongo Client Instace to connect to the MongoDB Database
// and perform various functions.
const MongoClient = require( 'mongodb' ).MongoClient;
// Store the URL of your MongoDB Server
const mongoURL = "mongodb://localhost:27017/";
// Stored the name of the Database you wanna connect to.
const dbName = "testdb";

// Create a new Mongo DB client that will connect to the MongoDB Server.
const client = new MongoClient(mongoURL);

// Connect the Client to the MongoDB Server.
client.connect( (err) => {

    // Error handling of some sort.
    if(err) throw err;

    console.log( 'connected!' );

    // Connect to the database you want to manage using the dbName you
    // stored earlier.
    const db = client.db( dbName );

    // Store the name of the collection you want to read from.
    // this can be created above near the dbName.
    const collectionName = "testCol"

    // Connect to the collection that you stored above.
    const collection = db.collection( collectionName );

    // Query the MongoDB database and log the results, if any.
    collection.find({}).toArray( (err, docs) => {
        console.log(docs);
    } );

} )

要消除newURLParser错误,只需使用

代码语言:javascript
复制
const client = new MongoClient( mongoURL, { useNewUrlParser: true } );

而不是

代码语言:javascript
复制
const client = new MongoClient(mongoURL);

这是指向MongoDB NodeJS快速入门的链接。http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55173723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档