Mongoose,如何清空集合

mou*_*777 3 mongoose mongodb node.js

我有以下 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();
Run Code Online (Sandbox Code Playgroud)

重点是,它工作正常并将所需的数据保存到我的集合中,但是如果我不删除每次执行的数据,数据库将继续增长。所以我打算实施类似于

db.blocks.remove({}) //where blocks is my collection
Run Code Online (Sandbox Code Playgroud)

这在 mongoconsole 中运行良好。但我找不到如何在代码中实现这一点

Tom*_*ert 10

您可以使用带有空过滤器的 deleteMany 运算符。

db.collection.deleteMany({})
Run Code Online (Sandbox Code Playgroud)

或使用您的模型:

await BlockModel.deleteMany({})
Run Code Online (Sandbox Code Playgroud)