简体   繁体   English

猫鼬,如何清空集合

[英]Mongoose, how to empty a collection

I've the following hapi.js server我有以下 hapi.js 服务器

const Hapi = require('hapi')
const Mongoose = require('mongoose')
const Wreck = require('wreck');


const server = new Hapi.Server({
    "host": "localhost",
    "port": 3000
})

Mongoose.connect('mongodb://localhost/myDB', { useNewUrlParser: true })

const BlockModel = Mongoose.model('block', {
    height: Number,
    size: Number,
    time: Number
})

server.route({
    method: "GET",
    path: "/",
    handler: async (request, h) => {

        Mongoose.model.blocks.remove({});    //<------This is the part of the code I intend to use to delete the collection

        const { res, payload } = await Wreck.get('https://api.url');
        let myJson = JSON.parse(payload.toString()).blocks
        console.log(myJson)
        for (let i = 0; i<myJson.length; i++) {
            var block = new BlockModel({  height: myJson[i].height, size: myJson[i].size, time: myJson[i].time });
            block.save();
        }
        console.log(myJson)

        return "test"
    }
})



server.start();

Point is, it works fine and saves the desired data to my collection, but ofc the database will keep growing if I dont delete the data on each execution.重点是,它工作正常并将所需数据保存到我的集合中,但是如果我不删除每次执行的数据,数据库将继续增长。 So I intend to implement something similar to所以我打算实现类似于

db.blocks.remove({}) //where blocks is my collection

Which works fine in the mongoconsole.这在 mongoconsole 中运行良好。 But I cant find how to implement this in the code但是我找不到如何在代码中实现它

You can use the deleteMany operator with an empty filter.您可以将 deleteMany 运算符与空过滤器一起使用。

db.collection.deleteMany({})

or with your model:或与您的模型:

await BlockModel.deleteMany({})

Empty all collections in a db清空数据库中的所有集合

const collections = await mongoose.connection.db.collections();

for (let collection of collections) {
    await collection.deleteMany({})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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