Create new record with mongoose
To create a new record with Mongoose, you can use the save()
method on a Mongoose model. Here is an example:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const User = mongoose.model('User', userSchema);
const newUser = new User({
name: 'John Doe',
email: '[email protected]'
});
newUser.save((err, user) => {
if (err) {
console.error(err);
} else {
console.log('New user created:', user);
}
});
In this example, we first define a Mongoose schema for a User
model, with two fields: name
and email
. We then create a new instance of the User
model using the new
keyword, passing in an object with the desired values for the name
and email
fields.
We then call the save()
method on the newUser
object, which will create a new document in the database and save it. The save()
method takes a callback function as an argument, which is called when the operation is complete. The callback function takes two arguments: err
(an error object if an error occurred) and user
(the newly created document).
Note that the save()
method will automatically generate a unique _id
field for the new document, if one is not provided.
You can also use the create()
method to create a new record, it's a shortcut for creating a new document and saving it:
User.create({
name: 'John Doe',
email: '[email protected]'
}, (err, user) => {
if (err) {
console.error(err);
} else {
console.log('New user created:', user);
}
});
This will create a new document and save it, and return the newly created document in the callback function.