【问题标题】:how can I drop my collection in mongoDB using mongoose?如何使用 mongoose 将我的收藏放在 mongoDB 中?
【发布时间】:2018-09-13 04:42:00
【问题描述】:

我已使用以下代码连接到 MongoDB。

mongoose.connect('mongodb://localhost:27017/samplecustomfields')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));

我在 app.js 文件中创建了模式模型和加载模型。你可以看到下面的代码

const customfields = [
{
  'id': 104,
  'name': '[Sample] Utility Caddy',
  'customfields': [
      {
          'id': 7,
          'product_id': 104,
          'name': 'Sample Utility',
          'text': 'canddy ofsuc'
      }
 }
]
require('./models/customfieldlists');
const productfields = mongoose.model('fields');

app.get('/api/products', (req, res, next) => {
productfields.insertMany(customfields, function(error, docs) {
  console.log('done');
});
res.send(customfields);
});

如何先删除我的“字段”集合,然后再调用“insertMany”查询。每次我收到“/api/products”这个请求时都会发生这种情况。

我已经把代码“productfields.dropCollection('fields');”上面的 insertMany 查询,但它不起作用。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:
    app.get('/api/products', (req, res, next) => {
        // Drop the 'fields' collection from the current database
        mongoose.connection.db.dropCollection('fields', function(err, result) {
             productfields.insertMany(customfields, function(error, docs) {
             console.log('done');
             res.send(customfields);
             });
        )};
    });
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      我从下面的 URL 发现没有使用 mongoose 删除集合的方法,但您可以从集合中删除数据。

      How to drop a database with Mongoose?

      下面是解决我问题的代码

      productfields.remove({}, function(err) {
          productfields.insertMany(customfields, function(error, docs) {
              res.send(docs);
           });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-20
        • 2015-08-07
        • 2022-01-05
        • 1970-01-01
        • 2015-05-02
        • 1970-01-01
        • 2015-08-22
        相关资源
        最近更新 更多