【问题标题】:Uspert multiple documents with MongoDB/Mongoose使用 MongoDB/Mongoose 访问多个文档
【发布时间】:2019-03-10 10:00:27
【问题描述】:

假设我有一个模型列表:

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

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

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

});

上面的签名肯定是错误的——我想做的是插入/更新满足条件的文档。

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

但我不知道它是否会在插入多个文档时起作用。

【问题讨论】:

标签: mongodb mongoose


【解决方案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);
            })
        }

所以,简短的回答是肯定的,你绝对可以这样做。更长的答案在上面:)我希望这对你有帮助。如果有任何问题,请告诉我,我会尽快回复。

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2014-02-09
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2018-09-20
    • 2015-05-25
    • 2017-10-01
    • 1970-01-01
    相关资源
    最近更新 更多