Nodejs Mongodb更新多个集合

时间:2018-02-19 11:54:56

标签: node.js mongodb express mongoose

在mongodb中现在有两个集合,用于事件和包。所以基本上模型看起来像这样

活动模型

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;

const bcrypt = require('bcrypt-nodejs');

const EventSchema = new Schema({
  _id: mongoose.Schema.Types.ObjectId,
  eventname: {
    type: String,
    required : true,
  },
  eventdesc: {
    type: String,
    required : true,
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Event', EventSchema);

包模型看起来像这样

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;

const bcrypt = require('bcrypt-nodejs');

const PackageSchema = new Schema({
  _id: mongoose.Schema.Types.ObjectId,
  eventpackages: {
    type: Object,
    required : false,
  },
  event: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Event'
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Package', PackageSchema);

这里我试图更新一个事件,所以当事件更新时,包也会更新。所以在nodejs中我做了这样的

    var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');


/* UPDATE EVENT */
router.put('/:id', function(req, res, next) {
  upload(req, res, function(err) {
    let EventData = {
      eventname       : req.body.eventname,
      eventdesc       : req.body.eventdesc, 
    }

    let EventPackages = {
      eventpackages : req.body.sections,
    }
    Event.findByIdAndUpdate(req.params.id, EventData, function (err, post) {
      if (err) return next(err);

      Package.findAndModify({
        query: { event: req.params.id },
        update: { $inc: { EventPackages } },
        new: true, 
        upsert: true 
      })
        res.json(post);
    });
  });
});



module.exports = router;

但它根本不起作用。如果我将删除包更新的代码,它将适用于事件。

所以有人可以告诉我如何使这项工作,以便我可以一次更新多个集合。

1 个答案:

答案 0 :(得分:0)

你可以试试这个,

    var query = {
              'event': req.params.id
              };
    var dataToUpdate = {
       $set: {
          ///
       }
};
Package.updateMany(query, datatoUpdate, function(err, result) {
       if (err) return handleError(err);

       return Promise.resolve(result);
});