【问题标题】:Save doesn't save any data保存不保存任何数据
【发布时间】:2018-06-05 21:56:20
【问题描述】:
我正在尝试将一些数据保存到本地 mongodb 数据库中。
我的架构如下所示:
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
passwordHash: String,
registerTimeStamp: { type: Number, default: Date.now() },
usersFollowing: [],
accountStatus: {
isBanned: { type: Boolean, default: false },
reason: { type: String, default: '' }
}
});
module.exports = mongoose.model('User', userSchema);
插入方法如下:
createUser(name, email, password) {
const passwordHash = "asdf";
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
});
user.save(console.log("saved"));
}
我的问题是,即使我使用正确的参数调用该方法,并且它打印“已保存”,但没有数据插入到数据库中。
谢谢!
【问题讨论】:
标签:
javascript
node.js
mongodb
mongoose
mongoose-schema
【解决方案1】:
首先,当你调用时:
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");
});
现在,您的插入方法出现错误。
变化:
_id: new mongoose.Types.ObjectId(),
与:
_id: new mongoose.Types.ObjectId,
括号是问题。
【解决方案2】:
问题是您只是在记录消息,而不是在数据库中保存用户。
为了做到这一点,首先你必须像这样导出用户模型:
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)
}
【解决方案3】:
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
passwordHash: String,
registerTimeStamp: { type: Number, default: Date.now() },
usersFollowing: [],
accountStatus: {
isBanned: { type: Boolean, default: false },
reason: { type: String, default: '' }
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
module.exports.createUser = function (name, email, password) {
const passwordHash = "asdf";
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
});
User.save(user , callback);
}