[英]findOneAndUpdate is not a function of mongoose
我知道之前已经回答了这个问题,但我似乎无法将更改实施到我正在使用的内容中。 我正在尝试创建一个日常命令来奖励用户执行 s.daily,我收到错误消息,
类型错误:profileData.findOneAndUpdate 不是 function
在 Object.execute (C:\Users--\Desktop\DiscBot\commands\daily.js:35:43)
在 module.exports (C:\Users--\Desktop\DiscBot\events\client\message.js:34:13)
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,在这里我使用 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,其中将配置文件制作成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,这里连接mongoose,然后传下去
mongoose.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
您正在尝试在文档上调用 findOneAndUpdate,您通过该文档在 message.js 中执行 function。 查看如何使用 findOneAndUpdate 的示例
我猜 findOneAndUpdate 需要两个相关参数(过滤器):要更新的数据和有效负载。
检查 mongoosedocs 了解更多信息。
大多数情况下,当您在 model 的实例而不是实际的 model 实例上调用 mongoose 中的 findOneAndUpdate 时,会发生此错误
所以而不是这个
var NewUser = new User(req.user);
NewUser.findOneAndUpdate...
做这个
var NewUser = new User(req.user);
User.findOneAndUpdate(
{ name: NewUser.name },
{ name: NewUser.name},
{ upsert: true });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.