在MongoDB / Mongoose中使用多个文档

时间:2018-10-04 23:25:33

标签: mongodb mongoose

说我有一个型号列表:

const documents = [{}, {}, {}];

我想将它们插入数据库或全部更新,但前提是要满足条件:

Model.update({isSubscribed: {$ne: false}}, documents, {upsert:true},(err, result) => {

});

上述签名肯定是错误的-我要做的是在满足条件的情况下插入/更新文档。

有以下批量API: https://docs.mongodb.com/manual/reference/method/Bulk.find.upsert/

但是我无法确定插入多个文档时是否可以使用。

1 个答案:

答案 0 :(得分:1)

想像一下这种情况:我们有一份雇员名单和某种形式的表格,可让他们一次全部受到惩罚,而不是一一列举:)

在后端,您将拥有例如addBulk函数。像这样:

惩罚控制器

module.exports = {

  addBulk: (req, res) => {
    const body = req.body;
    for (const item of body) {
      Penalty.create(item).exec((err, response) => {
        if (err) {
          res.serverError(err);
          return;
        }
      });
      res.ok('Penalties added successfully');
    }
  }

然后,您可能会在前端上有一个指向该路由和特定功能(端点)的API:

penaltyApi

import axios from 'axios';
import {baseApiUrl} from '../config';

const penaltyApi = baseApiUrl + 'penalty'

class PenaltyApi {

    static addBulk(penalties) {
        return axios({
            method: 'post',
            url: penaltyApi + '/addBulk',
            data: penalties
        })
    }

}

export default PenaltyApi;

...现在让我们创建一个表单和一些帮助函数。我将使用React进行演示,但是到今天结束时都是JS,对:)

// Lets first add penalties to our local state:

addPenalty = (event) => {
        event.preventDefault();
        let penalty = {
            amount: this.state.penaltyForm.amount,
            unit: this.state.penaltyForm.unit,
            date: new Date(),
            description: this.state.penaltyForm.description,
            employee: this.state.penaltyForm.employee.value
        };
        this.setState(prevState => ({
            penalties: [...prevState.penalties, penalty]
        }));
    }

Here we are mapping over our formData and returning the value and passing it to our saveBulkEmployees() function

    save = () => {
            let penaltiesData = Object.assign([], this.state.penalties);
            penaltiesData.map(penal => {
                penal.employeeId = penal.employee.id;
                delete penal.employee;

                return penaltiesData;
            });
            this.saveBulkEmployees(penaltiesData);
        }

    ...and finally, let's save all of them at once to our database using the Bulk API

        saveBulkEmployees = (data) => {
            PenaltyApi.addBulk(data).then(response => {
                this.success();            
                console.log(response.config.data)
                this.resetFormAndPenaltiesList()
            }).catch(error => {
                console.log('error while adding multiple penalties', error);
                throw(error);
            })
        }

因此,简短的回答是“是”,您绝对可以这样做。以上是更长的答案:)我希望这对您有所帮助。如有任何问题,请告诉我,我会尽快回答。