无法访问MongoDB属性或函数



我试图访问mongoose.connection中的属性或函数以检索DeleteManyDropCollection方法,但无法。我正在mongoose连接中启动express.js服务器。

mongoose
.connect(connection, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
mongoose.connection.db.dropCollection('database');
console.log('connected');
app.listen(5000);
})
.catch((error) => {
console.log(error);
});

我做错了什么?我已经尝试过搜索解决方案,我知道我不能使用Mongoose删除集合,我只能使用MongoDb删除数据。有人能帮我理解吗,在服务器运行时删除集合时我缺少了什么?

如果要删除mongoose中使用deleteMany的所有记录。

您必须指定集合的model才能在上应用操作

用于删除集合

MyModel.collection.drop();

删除所有记录

const mongoose = require('mongoose'); 

// Database connection
mongoose.connect(connectionUrl, { 
useNewUrlParser: true,
useUnifiedTopology: true
}); 

// MyCollection model 
const MyCollection = mongoose.model('MyCollection', { 
prop1: { type: String }, 
prop2: { type: Number } 
}); 

// Function call 
MyCollection.deleteMany({}).then(function(){ 
console.log("all records deleted"); // Success 
}).catch(function(error){ 
console.log(error); // Failure 
}); 

最新更新