【问题标题】:How to empty collection in mongodb using mongoose如何使用 mongoose 清空 mongodb 中的集合
【发布时间】:2020-05-30 04:04:44
【问题描述】:

在我的代码中,我动态插入一个集合,这个排序规则具有默认值

_id:ObjectId("5ed0d4d3fec27620043ee59d")
__v:0

我认为这是默认插入到 mongodb 中的。实际上我不需要这样,我正在尝试删除这两个 _id 和 __:0 但不起作用。

在我的代码下面:

   var NewModel = require(path.resolve('./models/newmodelschema.model.js'))(collectionName);
   NewModel.create({}, function(err, doc) { 
                NewModel.remove({_id:'',__v:0}, function(err) {
                    if (!err) {
                        console.log(err);
                        return;
                    } else {
                        console.log("Model empty");
                    }
                }); 
            });

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您可以在创建架构时使用选项 { _id: false, versionKey: false } 禁用 _id 和 _v。

    例子:

    1. 创建如下架构
        const NewModel = new mongoose.Schema({
          "name": { type: string}
        }, { _id: false, versionKey: false });
    
    1. 现在插入数据,
    NewModel.create({ "name": "foo"}, function(err, doc){
    console.log("data ", doc);
    });
    

    它应该打印出来,

    data { "name": "foo" }
    

    没有 _id 和 __v

    编辑 2: 你不能删除 _id 除非它是一个子文档

    PS:我建议保留这两个,要了解这些字段,请阅读 https://docs.mongodb.com/manual/core/document/#the-id-fieldhttps://mongoosejs.com/docs/guide.html#versionKey

    【讨论】:

    • { _id: false, versionKey: false } 这不起作用..{ versionKey: false } 只是起作用
    • 你有什么解决办法吗?
    • 你不能删除_id,_id: false 只对子文档有效。
    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 2019-01-14
    • 2021-08-14
    • 2020-01-31
    • 2023-01-10
    • 1970-01-01
    • 2014-06-05
    • 2016-01-29
    相关资源
    最近更新 更多