Sayeed Mahdi Mousavi
Sayeed Mahdi Mousavi

Reputation: 67

How we can update two collection in one query?

I have two models one is products with this attributes

const mongoose = require("mongoose");
const salesSchema =new mongoose.Schema({
    productname:{
        type:String,
        required:trud,
        unique:true
},
    productCount:{
        type:Number,
        required:true
    }
});
module.exports = mongoose.model("products",salesSchema);

and sales with this attributes

const mongoose = require("mongoose");
const salesSchema =new mongoose.Schema({
    productId:{
        type:mongoose.Schema.Types.ObjectId,
        ref:"products",
},
    salesCount:{
        type:Number,
        required:true
    }
});
module.exports = mongoose.model("sales",salesSchema);

when some one act with sales it should decrease or increase automatically update the count product table.

Upvotes: 0

Views: 70

Answers (1)

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

Yo can only run a query against one collection at any given time. So you have to do those queries separately. However, if you're using MongoDB Atlas for hosting, you can use their Trigger functionality to listen to changes to your sales collection. When an insert is triggered, run a query towards products where you reduce the quantity.

If you're not using Atlas you can use MongoDB Change Streams available via the Node SDK to do the same thing as triggers, listen to inserts to a specific collection. (You can do this on any environment, however you need to configure a Replica Set for this to work)

So what I'm saying is; Only insert the sales document, and let a watcher handle the product collection updates after.

const changeStream = salesSchema.collection.watch([{
    $match: {
        operationType: 'insert',
    },
}], {
    fullDocument: 'updateLookup',
})

changeStream.on('change', changeEvent => {
    const salesDocument = changeEvent.fullDocument

    // Run the product update here
})

Upvotes: 1

Related Questions