带有Upsert True的Mongo Db查询

时间:2020-01-25 12:53:49

标签: arrays node.js mongodb express mongoose

我正在编写一个upsert为true的mongoDb查询,但收到“更新路径\'marketRatio \'会在\'marketRatio \'处造成冲突的错误

我的代码是:

router.post('/testing', async (req, res)=>{

try {

    let providerId = req.body.providerId;
    let arrayProvider = {
        providerId : providerId,
        counter: 5
    };

    let doc = await gameRatio.findOneAndUpdate(
        {  userId : req.body.userId }, 
        {
            userId : req.body.userId,
            username : "mohit8982",
            marketRatio : arrayProvider,
            $inc: {
                totalBids : 5,
                totalPending : 5,
                totalBidsAmount : 55,
                "marketRatio.$[id].counter": 2 
            }
        }, 
        {   arrayFilters : 
                [ 
                    {"id.providerId" :  providerId }
                ],
                multi : true ,
                new: true,
                upsert: true  
        }); 

    console.log(doc);
    res.json(doc);

} catch (error) 
{

    console.log(error);
    let err = JSON.parse(error);
    res.json(err);

}});

模式是:

const  RatioAnalysys = new mongoose.Schema({
userId: {
    type: mongoose.Schema.Types.ObjectId,
    required: false
},
username: {
    type: String,
    required: false
},
totalBids:{
    type: Number,
    required: false
},
totalWin:{
    type: Number,
    required: false
},
totalLoss:{
    type: Number,
    required: false
},
totalPending:{
    type: Number,
    required: false
},
totalBidsAmount:{
    type: Number,
    required: false,
},
totalWinAmount:{
    type: Number,
    required: false
},
marketRatio : {
    type: Array,
    required: false
}}

我想要的输出就像我将数据插入数据库时​​一样,此查询将运行, 然后有一个数组市场比率,其中我有2个col,ProviderId和Counter, 如果providerId匹配,我想增加计数器,否则我要将带有计数器的providerId推入marketRatio数组

0 个答案:

没有答案