[英]Can't save data into MongoDB server using Mongoose
I'm trying to integrate a database into my DiscordBot app and currently having a problem with inputting new user into MongoDB using Mongoose.我正在尝试将数据库集成到我的 DiscordBot 应用程序中,目前在使用 Mongoose 将新用户输入 MongoDB 时遇到问题。 The console also show no err at all.
控制台也完全没有错误。
const mongoose = require('mongoose')
const User = require('../models/userModels')
module.exports = message => {
User.findOne({userID:message.author.id}, (err,user)=>{
if(user == null){ //Create new db collections if none was found
const user = new User({
_id: mongoose.Types.ObjectId(),
userID: message.author.id,
username: message.author.username,
role: ["default"],
balance: 0,
level: 1,
exp: 0,
lastAttendance: message.createdAt
})
user.save()
.then(result => {
console.log(result)
message.reply("Information saved")
})
.catch(err => console.log.err)
}
}
This is my model code:这是我的 model 代码:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var userSchema = new Schema({
_id: Schema.Types.ObjectId,
userID:{type: String, unique:true, required:true},
username: String,
balance:{type: Number, require:true},
role: {type:String, enum: ['default','admin']},
level:{type: Number, require:true},
exp:{type: Number, require:true},
lastAttendance: Date
})
module.exports = mongoose.model('Users', userSchema)
The reason why you are not getting error logs is because of the console.log
syntax in the catch
statement is wrong.您没有收到错误日志的原因是因为
catch
语句中的console.log
语法是错误的。 Change console.log.err
to console.log(err)
将 console.log.err 更改为
console.log.err
console.log(err)
The type defined for role
in the userSchema
is String
and you are passing it as array role: ["default"]
.为
userSchema
中的role
定义的类型是String
,您将其作为数组role: ["default"]
。 You need to change this to role: "default"
.您需要将其更改为
role: "default"
。
Also on success, if you are trying to set the key reply
to the message
object with value "Information saved"
then you should replace message.reply("Information saved")
with message.reply = "Information saved"
同样在成功时,如果您尝试使用值
"Information saved"
的信息”设置对message
object 的密钥reply
,那么您应该将message.reply("Information saved")
替换为message.reply = "Information saved"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.