mongoose 我一直在等待campgrounds.deleteMany()函数,但它仍然在10秒后缓冲

1rhkuytd  于 2023-03-18  发布在  Go
关注(0)|答案(1)|浏览(103)
const path = require('path')
 const mongoose = require('mongoose')
 const cities = require('./cities')
 const Campground = require('../views/models/campground')
 const {descriptors,places} = require('./seedhelpers')

 mongoose.connect('mongodb://localhost:27017/yelp-camp', {
      useNewUrlParser:true,
      //useCreateIndex:true,
      //useFindAndModify:true,
      useUnifiedTopology:true
 })

 db = mongoose.connection;
 db.on("error", console.error.bind(console, "connection ERROR"));
 db.once("open", ()=>{
 console.log("Database connection open")
 })

 const sample = array => array[Math.floor(Math.random() * array.length )]

 const seedDB =  async()=>{
     await Campground.deleteMany({});
     for(let i=0; i<50; i++){
     const random1000 = Math.floor(Math.random() * 1000)
     const price = Math.floor(Math.random()*20)*10
     const camp = new Campground({
         author:'63dbcd28bd0379985929400c',
         location: `${cities[random1000].city}, ${cities[random1000].state} `, 
         title: `${sample(descriptors)} ${sample(places)}`,
         image:'https://source.unsplash.com/collection/483251',
         description:"Lorem ipsum, dolor sit amet consectetur adipisicing elit. Delectus labore magnam          reiciendis ex corrupti, nobis, obcaecati alias laboriosam voluptatum, cumque dignissimos accusamus? Voluptatibus accusamus voluptatum nulla vel doloribus, delectus voluptatem?",
         price
         })
         await camp.save()
     }
}

 seedDB().then(()=>{
 mongoose.connection.close();
})

显示10秒后缓冲。但我在这里等待。我想删除所有的营地,并使一套新的营地每次我运行的文件。所以我给了它。

egmofgnx

egmofgnx1#

当Mongoose说它在缓冲命令时,这意味着你在连接建立之前发出了命令,在命令上使用await并不能解决这个问题。
您的问题可能是由于在连接字符串中使用了localhost,这可能会解析为该主机名的IPv6地址(::1)。MongoDB通常只侦听IPv4等效地址127.0.0.1,这意味着Mongoose(以及底层MongoDB库)试图连接到错误的地址。
修复方法是在连接字符串中显式使用IPv4地址:

mongodb://127.0.0.1:27017/yelp-camp

相关问题