我正在编写一个机器人,它能够从我拥有的.json文件中随机 Select 一张卡,并应该将其添加到用户的卡 list 中.每一张卡都有自己的唯一代码.如果用户之前有这张卡,它将在数量上加1.否则,它应该在卡片数组下创建一个随机卡片的数据.

因此,我try 首先从用户的库存中搜索代码,然后如果它不存在,则填充它.

然而,即使没有返回错误,每次我使用该命令获取卡时,MongoDB上的数组仍然是空的.

const { idolname, group, era, rarity, code, image, qty } = cards ?? {};

const newCard = { "cards.code": `${code}` };
         const updateInv = { $inc: { "cards.$.qty": 1 }};

        let searchInv = await UserProfile.findOne({newCard});

        if (!searchInv) {
            UserProfile.updateOne({ $push: { "cards": { "cards.$.idolname": `${idolname}`, "cards.$.era": `${era}`, "cards.$.groupp": `${group}`, "cards.$.rarity": `${rarity}`, "cards.$.code": `${code}`, "cards.$.qty": '1'}}});
        } else {
            UserProfile.updateOne(newCard, updateInv);
        }

以下是架构的设置方式

const { time } = require('discord.js');
const { Schema, model } = require('mongoose');

const userProfileSchema = new Schema({
    userName: {
        type: String,
    },
    userId: {
        type: String,
        required: true,
    },
    balance: {
        type: Number,
        default: 0,
    },
    lastDailyCollected: {
        type: Date,
    },
    lastDrop: {
        type: Date,
    },
    cards: [ {
        idolname: String,
        group: String,
        era: String,
        rarity: Number,
        code: String,
        image: String,
        qty: Number,
        }],
},
{ timestamps: true }
);

module.exports = model('UserProfile', userProfileSchema);

我不确定是不是因为我试图添加随机卡的名字,把事情搞得一团糟--因为我不仅仅是在推动一个设定值.

或者,问题可能是卡数据库位于本地.json上,而不是上传到MongoDB中?

请帮帮我,我太糊涂了,请给我指个方向.

我对编程非常陌生,并试图寻找解决方案,但似乎两者都无法实现.

推荐答案

这里有一个简单的例子,首先判断用户,如果他们有正确的卡,那么在qty属性上加1.但如果他们没有卡,结果将是null,因此您可以向cards数组添加新卡.有一些更复杂的方法可以使用Aggregation $set阶段在一个查询中完成,但这种方法更容易操作:

try{
   // Find the user but only match if they already have cards.code === code
   // If they exist then just increment the qty using $ positional operator 
   const incUser = await UserProfile.findOneAndUpdate(
      {
         userId: interaction.user.id,
         "cards.code": code
      }, 
      { $inc: { "cards.$.qty": 1 } }, 
      {new: true}
   );
   // If no matches were found it means we need to push a new card to this user
   if(!incUser){ 
      const pushUser = await UserProfile.findOneAndUpdate(
         { userId: interaction.user.id }, 
         { 
            $push: { 
               cards: { 
                  idolname: idolname, 
                  era: era, 
                  group: group, 
                  rarity: rarity, 
                  code: code, 
                  qty: 1
               }
            }
         }, 
         {new: true}
      );
   }
   return res.status(201).json({
      message: 'User updated'
   })
}catch(err){
   console.log(err);
   return res.status(500).json({
      message: 'Error on server'
   })
}

Node.js相关问答推荐

无法在我的 node 项目中转让Google Drive v3 API中的所有权

仅当所需文档是最后一个文档时才更新MongoDB,否则插入

如何在Mongoose中调用动态Collection ?

JEST模拟由http服务器控制器导入的ES模块

npm错误;无法解析依赖项:npm ERR!对等webpack@;5.x.x;来自@webpack-cli/serve@2.0.5";

表达 js 错误处理程序在第一个之后被忽略

NodeJS `request` 库无法通过 multipart-form-data 将文件发布到 dotnet 服务器

错误:无法为 /blog 收集页面数据并且在 object.fetch 处获取失败

node_modules/preact/src/jsx.d.ts:2145:22 - 错误 TS2304:找不到名称SVGSetElement

加速 sequelize ORM 中的查询

使用react 组件加载特定 DIV 而无需重新加载整个页面

根据 mongoDB 中存在的唯一字符串生成唯一字符串的最佳方法

如何更新 MongoDB 中对象数组中的键?

Cassandra node.js 驱动程序有替代品吗?

我可以向NPM添加调试脚本吗?

使用 Node.JS,如何按时间顺序获取文件列表?

create-react-app,安装错误(找不到命令)

Nodejs续集批量更新

为什么 Node.js 被命名为 Node.js?

FireStore 如果不存在则创建一个文档