mongodb将数据插入对象数组并更新 [英] mongodb insert data into the array of objects and update it

查看:786
本文介绍了mongodb将数据插入对象数组并更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要投票,它看起来像是一个对象数组,看起来像用户的ID和他设置的值.

I need to make a vote, it looks like an array of objects, look like the user’s ID and the value that he set.

如果用户已经投票,但是更改了其值,则需要更改该用户在对象数组中的费率值.

If the user has already voted, but changed his value, you need to change the value of the rate in the array of objects for this user.

我需要创建一个对象数组,将数据插入其中,例如{rate:3,user:"asdr2r24f2f42f24"}},如果用户已经对该数组进行了投票,那么您需要更改给定的用户

I need to make an array of objects into which data will be inserted like this {rate: 3, user: "asdr2r24f2f42f24"} and if the user has already voted in this array, then you need to change the value rate of the given user

我已经尝试做某事,但是在我看来,您可以写出更好的东西,可以帮忙吗?

I already tried to do something, but it seems to me you can write something better, can you help?

JSON https://jsoneditoronline.org/?id=442f1dae0b2d4997ac69d44614e55aa6

 router.post('/rating', (req, res) => {
  console.log(req.body)
  // { id: 'f58482b1-ae3a-4d8a-b53b-ede80fe1e225',
  //   rating: 5,
  //   user: '5e094d988ddbe02020e13879' }

  Habalka.find({
    _id: req.body.id
  })
    .then(habalka => {

      // here I need to check whether the user has already voted or not, and from this whether to add an object with it or update the number
      Habalka.updateOne(
        {_id: req.body.id},
        {$push: {rating: {rate: req.body.rating, user: req.body.user}}}
      )
        .then(e => {
          console.log(e)
        })
    });
});

模式

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

const HabalkaSchema = new Schema({
  _id: {
    type: String
  },
  bio: {
    firstname: String,
    lastname: String,
    middlename: String,
    company: String
  },
  rating: [

  ],
  files: [
    {
      _id: {
        type: String
      },
      destination: {
        type: String
      },
      filename: {
        type: String
      },
      path: {
        type: String
      },
      folder: {
        type: String
      },
      info: {
        size: {
          type: Number
        },
        mimetype: {
          type: String
        },
        encoding: {
          type: String
        },
        originalname: {
          type: String
        },
        fieldname: {
          type: String
        },
      },
      date: {
        type: Date,
        default: Date.now
      },
      bio: {
        type: Object
      },
      userId: String,
      guessId: {},
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});
module.exports = Habalka = mongoose.model('habalka', HabalkaSchema);

推荐答案

这是一个聚合查询,可在rating数组中插入新用户或更新现有用户的评分: 对于示例代码,req.body.idreq.body.userreq.body.rating设置如下:

This is an aggregation query which inserts a new user or updates the rating of existing user in the rating array: The req.body.id, req.body.user and req.body.rating are set as follows for the example code:

var ID = 1, INPUT_USER = "new user", INPUT_RATE = 5;

const matchStage = { $match: { _id: ID } };
const facetStage = {
  $facet: {
      new_user: [
        { $match: { "rating.user": { $not: { $eq: INPUT_USER } } } },
        { $addFields: { rating: { $concatArrays: [ "$rating", [ { user: "new user", rate: INPUT_RATE } ] ] } } },
      ],
      user: [   
        { $match: { "rating.user": INPUT_USER } },
        { $addFields: { 
               rating: {
                   $map: { 
                       input: "$rating",
                       as: "r",
                       in: {
                       $cond: [ { $eq: [ "$$r.user", INPUT_USER ] },
                                { user: "$$r.user", rate: { $add: [ "$$r.rate", INPUT_RATE ] } },
                                "$$r"
                              ]
                       }
                   }
               }
        } }
      ]
  }
};
const projectStage = { 
     $project: { 
         result: { $arrayElemAt: [ { $concatArrays: [ "$user", "$new_user" ] }, 0 ] }  
     }
};

const queryPipeline = [
    matchStage,
    facetStage,
    projectStage
];

// Run the aggregation query and get the modified document
// after applying the user and rate data in the rating array.
// The result of the aggregation is used to update the collection.
col.aggregate(queryPipeline).toArray( ( err, docs ) => {

    console.log("Aggregation output:");
    console.log( JSON.stringify( docs[0] ) );

    // Update the aggregate result to the collection.
    col.updateOne( { _id: docs[0].result._id },
                   { $set: { rating: docs[0].result.rating } }, 
                   ( err, updateResult ) => {
                       console.log( 'Updated count: ', updateResult.matchedCount );
                    }
     );

     callback(docs);
} );

示例收集文档:

{ "_id" : 1, "rating" : [ { "user" : "user1", "rate" : 2 } ] }

如果输入为var ID = 1, INPUT_USER = "new user", INPUT_RATE = 5;,则更新后的文档将为:

If the input is var ID = 1, INPUT_USER = "new user", INPUT_RATE = 5; the updated document will be:

{ "_id" : 1, "rating" : [ { "user" : "user1", "rate" : 2 }, { "user" : "new user", "rate" : 5 } ] }

如果输入为var ID = 1, INPUT_USER = "user1", INPUT_RATE = 5;,则更新后的文档将为:

If the input is var ID = 1, INPUT_USER = "user1", INPUT_RATE = 5; the updated document will be:

{ "_id" : 1, "rating" : [ { "user" : "user1", "rate" : 7 } ] }

这篇关于mongodb将数据插入对象数组并更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆