Reputation: 23
I'm trying to save some data into a local mongodb database. My schema looks as follows:
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);
and the insert Method looks like this:
createUser(name, email, password) {
const passwordHash = "asdf";
const user = new User({
_id: new mongoose.Types.ObjectId(),
name,
email,
passwordHash
});
user.save(console.log("saved"));
}
my problem is, that even though I called the method with the right arguments, and it prints "saved", no data is inserted into the database.
Thanks!
Upvotes: 2
Views: 64
Reputation: 122
First of all, when you call:
user.save(console.log("saved"));
The console will print "saved" no matter if you get or not an error. So maybe you are getting an error without a proper handler. If you really want to know what is happening with your user instance:
user.save()
.then(() => console.log("saved"))
.catch((error) => console.log(error));
If you want to use callbacks instead of promises:
user.save(function(error) {
if(error) throw error;
console.log("saved");
});
Now, there is an error in your insert method.
Change:
_id: new mongoose.Types.ObjectId(),
With:
_id: new mongoose.Types.ObjectId,
The parenthesis is the problem.
Upvotes: 1
Reputation: 623
The problem is that you are just logging the message, not saving the user in your database.
In order to do that, first you have to export the user model doing something like this:
const UserModel = mongoose.model('User', userSchema)
module.exports = UserModel
Next, in the same file where you have the createUser method, you import the UserModel. Then in your createUser method, you call the .save method but from your model just imported, sending the just created user:
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)
}
Upvotes: 0
Reputation: 281
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);
}
Upvotes: 0