代码之家  ›  专栏  ›  技术社区  ›  adam tropp

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

  •  0
  • adam tropp  · 技术社区  · 5 年前

    db.questions.count() 我得到1,我在shell中创建的1。但如果我在我的应用程序中做同样的事情:

    ...
    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实例运行正常。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Ahmad Shahzad    5 年前

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

    // 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);
        } );
    
    } )
    

    const client = new MongoClient( mongoURL, { useNewUrlParser: true } );
    

    而不是

    const client = new MongoClient(mongoURL);
    

    http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/