简体   繁体   中英

MongoDB and express, connection timeout when attempting an insertMany

I'm starting to learn node, express, and mongodb.

In one of my getting started exercises I'm trying to do single and multiple inserts into a collection called documents .

Single inserts work fine:

let express = require('express')
let app = express()

let MongoClient = require('mongodb').MongoClient
let assert = require('assert')
let url = 'mongodb://localhost:27017/test'

app.get('/testInsert',(req,res) => {
    MongoClient.connect(url, (err, db) => {
        assert.equal(null, err)
        console.log("Connected to mongo server")

        let collection = db.collection('documents')

        // this works fine
        collection.insertOne({test: 'worked'}, (err, rec) => {
            assert.equal(null, err)
            assert.equal(1, rec.insertedCount)
            console.log('single insert result: ' + rec)
            db.close();
            res.send('single insert result: ' + rec)
        })

    })
})

But when I try to insert many I get a timeout:

let express = require('express')
let app = express()

let MongoClient = require('mongodb').MongoClient
let assert = require('assert')
let url = 'mongodb://localhost:27017/test'

app.get('/testInsert',(req,res) => {
    MongoClient.connect(url, (err, db) => {
        assert.equal(null, err)
        console.log("Connected to mongo server")

        let collection = db.collection('documents')

        // This fires
        console.log('about to start insert many')
        collection.insertMany([{greeting: 'hi'}, {greeting: 'hey'}, {greeting: 'yo'}]), (err, recs) => {
            // I never get past here
            console.log('finished insert many')
            assert.equal(err,null)
            assert.equal(3,recs.result.n)
            assert.equal(3,recs.insertedCount)
            db.close();
            res.send("multi insert result: " + recs)
        }
    })
})

When I try hitting the endpoint I get a request timeout: 错误信息

But when I check mongo the records are definitely inserted: 插入记录

I'm assuming I'm doing something wrong with the mongo insert because I never get to the first line of my callback. Is there something that I'm doing wrong when trying to insert multiple documents into mongo?

On this line in your code:

"collection.insertMany([{greeting: 'hi'}, {greeting: 'hey'}, {greeting: 'yo'}]), (err, recs) "

There shouldn't be a closing parens ) after the closing bracket ]. I think if you fix that it should help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM