在不同集合的保存/更新中的猫鼬更新文档

时间:2018-10-12 11:41:23

标签: node.js mongodb mongoose

我有两个互相引用的集合:

const mongoose = require('mongoose');
const productVariantSchema = mongoose.Schema({
   _id:           mongoose.Schema.Types.ObjectId,
   name:         {type: String,  required: true},
   price:        {type: String,  required: true},
   reduced:      {type: Boolean, required: true},
   reducedPrice: {type: String,  required: false},
   manufacturer: {type: mongoose.Schema.Types.ObjectId, ref: 'Manufacturer', required: true},
   product:      {type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true}
});

module.exports = mongoose.model('ProductVariant', productVariantSchema);


const mongoose = require('mongoose');
const manufacturerSchema = mongoose.Schema({
   _id:               mongoose.Schema.Types.ObjectId,
   name:             {type: String,  required: true},
   street:           {type: String,  required: true},
   streetNumber:     {type: Number,  required: true},
   postcode:         {type: Number,  required: true},
   country:          {type: String,  required: true},
   productVariants: [{type: mongoose.Schema.Types.ObjectId, ref: 'ProductVariant', required: true}]
});

module.exports = mongoose.model('Manufacturer', manufacturerSchema);

保存productVariant时,我想更新制造商文档以将创建的productVariant添加到其数组中:

exports.productVariant_createProductVariant = (req, res, next) => {
Manufacturer.findById(req.body.manufacturerID)
    .then(manufacturer => {
        if(!manufacturer) {
            return res.status(404).json({
                message: 'Manufacturer not found',
            });
        }
        Product.findById(req.body.productID)
            .then(product => {
                if (!product) {
                    return res.status(404).json({
                        message: 'Product not found',
                    });
                }
            })
            const productVariant = new ProductVariant({
                _id:          new mongoose.Types.ObjectId(),
                name:         req.body.name,
                price:        req.body.price,
                reduced:      req.body.reduced,
                reducedPrice: req.body.reducedPrice,
                manufacturer: req.body.manufacturerID,
                product:      req.body.productID
            });
            return productVariant.save()
    })
    .then(result => {

        // Somehow works but doesn't seem right
        Manufacturer.findByIdAndUpdate(req.body.manufacturerID, {$push: {productVariants: result._id}}, function(err) {
            if(err) {
                res.status(500).json({
                    error: err
                });
            }
        });

        res.status(201).json({
            message: 'Created Product variant',
            productVariant: {
                _id:          result._id,
                name:         result.name,
                price:        result.price,
                reduced:      result.reduced,
                reducedPrice: result.reducedPrice,
                manufacturer: result.manufacturer,
                product:      result.product
            },
            request: {
                type: 'GET',
                url: 'http://localhost:3000/productVariants/' + result._id
            }
        });
    })
    .catch(err => {
        res.status(500).json({
            error: err
        });
    });

}

当前,在保存productVariant之后,我正在.then函数中更新制造商文档。如果碰巧出现错误,它将被忽略。另外,我认为代码看起来有点多余,因为在保存productVariant之前,我检查了其Manufacturer是否存在,这是保存productVariant的要求。但是,只有成功保存productVariant时,我才能更新制造商文档。

当我想更改制造商时要更新productVariant时,也会出现相同的问题:

exports.productVariant_patchProductVariant = (req, res, next) => {
   const id = req.params.id;
   const updateOps = {};
   for(const ops of req.body) {
       updateOps[ops.propName] = ops.value;
   }
   ProductVariant.update({_id: id}, { $set: updateOps })
       .exec()
       .then(result => {
           res.status(200).json({
               message: 'ProductVariant updated',
               request: {
                   type: 'GET',
                   url: 'http://localhost:3000/productVariants/' + id
               }
           });
       })
       .catch(err => {
           res.status(500).json({error: err});
       });

       // Update old and new Manufacturer doc here ???

}

基本上,如果我想更改其制造商(从旧的制造商文档中删除productVairant并将其插入新的制造商文档中),则需要在productVariant的更新功能中更新两个制造商文档,但我不确定该如何处理正确。

我希望有人可以帮助我解决这个问题。

预先感谢

0 个答案:

没有答案