我试图访问mongoose.connection
中的属性或函数以检索DeleteMany
或DropCollection
方法,但无法。我正在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
});