简体   繁体   English

findOneAndUpdate 不是 mongoose 的 function

[英]findOneAndUpdate is not a function of mongoose

I know this question has been answered before but I can't seem to implement the changes into what im working with.我知道之前已经回答了这个问题,但我似乎无法将更改实施到我正在使用的内容中。 I'm trying to create a daily command that rewards a user for doing s.daily, I get the error,我正在尝试创建一个日常命令来奖励用户执行 s.daily,我收到错误消息,

TypeError: profileData.findOneAndUpdate is not a function类型错误:profileData.findOneAndUpdate 不是 function

at Object.execute (C:\Users--\Desktop\DiscBot\commands\daily.js:35:43)在 Object.execute (C:\Users--\Desktop\DiscBot\commands\daily.js:35:43)

at module.exports (C:\Users--\Desktop\DiscBot\events\client\message.js:34:13)在 module.exports (C:\Users--\Desktop\DiscBot\events\client\message.js:34:13)

daily.js, one having error at line 35 for findOneAndUpdate is not a function daily.js,第 35 行的 findOneAndUpdate 错误不是 function

const Schema = require('../models/profileSchema')
//cache users that claim daily rewards
let claimedCache = []

const clearCache = () => {
  claimedCache = []
  setTimeout(clearCache, 1000 * 60 * 10)
}
clearCache()
//message to make it easier later
const alreadyClaimed = 'You have already claimed your daily rewards'

module.exports = {
    name: "daily",
    aliases: ["day", "d"],
    permissions: [],
    description: "Claim your daily rewards!",
    async execute(message, args, cmd, client, Discord, profileData) {

    const { serverID, member } = message
    const { id } = member
//If user is in cache return message
    if (claimedCache.includes(id)) {
      console.log('Returning from cache')
      message.reply(alreadyClaimed)
      return
    }
//Put everything in object for later
    const obj = {
      guildId: serverID,
      userId: id,
    }
//Results is an update that either updates if is user is not in array and doesn't if they are, but it doesn't know what findOneAndUpdate is (thought it was just a mongo/mongoose function??)
      try {
        const results = await profileData.findOneAndUpdate(obj)

        console.log('RESULTS:', results)

        if (results) {
          const then = new Date(results.updatedAt).getTime()
          const now = new Date().getTime()

          const diffTime = Math.abs(now - then)
          const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24))

          if (diffDays <= 1) {
            claimedCache.push(id)

            message.reply(alreadyClaimed)
            return
          }
        }
//after the update increase coins by 50 and send claimed message
        await profileRewardsSchema.findOneAndUpdate(obj, obj, {
          upsert: true,
        })

        claimedCache.push(id)
        const amount = 50;
        await profileModel.findOneAndUpdate(
            {
              userID: id,
            },
            {
              $inc: {
                coins: amount,
              },
            }
          );
        message.reply('You have claimed your daily rewards!')
      }catch (err) {
        console.log(err);
      }
    }
}

message.js, heres where I make profileModel a thing using mongoose to pass it into my commands message.js,在这里我使用 mongoose 将 profileModel 传递到我的命令中

const profileModel = require("../../models/profileSchema");
const config = require('../../config.json');

module.exports = async (Discord, client, message) => {
    //command handler start

    const prefix = 's!';
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    //database junk
    let profileData;
    try {
      profileData = await profileModel.findOne({ userID: message.author.id });
      if (!profileData) {
        let profile = await profileModel.create({
          userID: message.author.id,
          serverID: message.guild.id,
          coins: 10,
          bank: 0,
        });
        profile.save();
      }
    } catch (err) {
      console.log("Error creating new database profile");
    }
    
    const args = message.content.slice(prefix.length).split(/ +/);
    const cmd = args.shift().toLowerCase();
  
    const command = client.commands.get(cmd)  || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
   
    if(!command) return message.channel.send(":x: This is not a valid command");
    try {
    command.execute(message, args, cmd, client, Discord, profileData);
    } catch (err) {
      message.reply('There was an error executing that command!');
    }
};

profileSchema.js, Where profile is made into mongo database profileSchema.js,其中将配置文件制作成mongo数据库

const mongoose = require("mongoose");

const profileSchema = new mongoose.Schema({
  userID: { type: String, require: true, unique: true },
  serverID: { type: String, require: true },
  coins: { type: Number, default: 10 },
  bank: { type: Number },
},
  {
    timestamps: true,
  }
)
const model = mongoose.model("ProfileModels", profileSchema);
module.exports = model;

main.js, where mongoose is connected, then passed on main.js,这里连接mongoose,然后传下去

mongoose.connect(process.env.MONGODB_SRV, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false
})

You are trying to call findOneAndUpdate on the document, which you passed to execute function at message.js.您正在尝试在文档上调用 findOneAndUpdate,您通过该文档在 message.js 中执行 function。 Check the example of how to use findOneAndUpdate查看如何使用 findOneAndUpdate 的示例

https://mongoosejs.com/docs/tutorials/findoneandupdate.html https://mongoosejs.com/docs/tutorials/findoneandupdate.html

I guess findOneAndUpdate takes two relevant parameters (filter): the data to be updated, and the payload.我猜 findOneAndUpdate 需要两个相关参数(过滤器):要更新的数据和有效负载。

Check mongoosedocs for more info.检查 mongoosedocs 了解更多信息。

Most of the time this error happen when you call findOneAndUpdate in mongoose when you call it on the instance of the model NOT the actual model大多数情况下,当您在 model 的实例而不是实际的 model 实例上调用 mongoose 中的 findOneAndUpdate 时,会发生此错误

so instead of this所以而不是这个

var NewUser = new User(req.user);
NewUser.findOneAndUpdate...

do this做这个

var NewUser = new User(req.user);
User.findOneAndUpdate(
        { name: NewUser.name },
        { name: NewUser.name},
        { upsert: true });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM