Javascript 不保存';不要保存任何数据
我正在尝试将一些数据保存到本地mongodb数据库中。 我的模式如下所示:Javascript 不保存';不要保存任何数据,javascript,node.js,mongodb,mongoose,mongoose-schema,Javascript,Node.js,Mongodb,Mongoose,Mongoose Schema,我正在尝试将一些数据保存到本地mongodb数据库中。 我的模式如下所示: const mongoose=require('mongoose'); const userSchema=mongoose.Schema({ _id:mongoose.Schema.Types.ObjectId, 名称:String, 电子邮件:String, passwordHash:String, registerTimeStamp:{type:Number,默认值:Date.now()}, 以下用户:[], 帐户
const mongoose=require('mongoose');
const userSchema=mongoose.Schema({
_id:mongoose.Schema.Types.ObjectId,
名称:String,
电子邮件:String,
passwordHash:String,
registerTimeStamp:{type:Number,默认值:Date.now()},
以下用户:[],
帐户状态:{
IsBanked:{type:Boolean,默认值:false},
原因:{类型:字符串,默认值:''}
}
});
module.exports=mongoose.model('User',userSchema)代码>首先,当您呼叫时:
user.save(console.log("saved"));
无论您是否收到错误,控制台都将打印“已保存”。因此,如果没有适当的处理程序,可能会出现错误。如果您确实想知道您的用户实例发生了什么情况:
user.save()
.then(() => console.log("saved"))
.catch((error) => console.log(error));
如果要使用回调而不是承诺:
user.save(function(error) {
if(error) throw error;
console.log("saved");
});
现在,insert方法中有一个错误
更改:
_id: new mongoose.Types.ObjectId(),
与:
括号就是问题所在。问题在于您只是在记录消息,而不是将用户保存在数据库中
为此,首先必须导出用户模型,如下所示:
const UserModel = mongoose.model('User', userSchema)
module.exports = UserModel
接下来,在具有createUser方法的同一文件中,导入UserModel。然后在createUser方法中,调用.save方法,但从刚导入的模型中,发送刚创建的用户:
const UserModel = require('../pathtothefile') //Here you specify the path of the user-model file
createUser(name, email, password) {
const passwordHash = "asdf"
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
})
return UserModel.save(user)
}
我明白你的问题了。你在使用mongoDB。
const UserModel = mongoose.model('User', userSchema)
module.exports = UserModel
const UserModel = require('../pathtothefile') //Here you specify the path of the user-model file
createUser(name, email, password) {
const passwordHash = "asdf"
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
})
return UserModel.save(user)
}