I've found two approach to create new document in nodejs when I work with mongoose.
First:
var instance = new MyModel();
instance.key = 'hello';
instance.save(function (err) {
//
});
Second
MyModel.create({key: 'hello'}, function (err) {
//
});
Is there any difference?
Yes, the main difference is the ability to do computations before you save or as a reaction to information that comes up while you're building your new model. The most common example would be making sure the model is valid before trying to save it. Some other examples might be creating any missing relations before saving, values that need to be calculated on the fly based on other attributes, and models that need to exist but could potentially never be saved to the database (aborted transactions).
So as a basic example of some of the things you could do:
var instance = new MyModel();
// Validating
assert(!instance.errors.length);
// Attributes dependent on other fields
instance.foo = (instance.bar) ? 'bar' : 'foo';
// Create missing associations
AuthorModel.find({ name: 'Johnny McAwesome' }, function (err, docs) {
if (!docs.length) {
// ... Create the missing object
}
});
// Ditch the model on abort without hitting the database.
if(abort) {
delete instance;
}
instance.save(function (err) {
//
});
This code is for saving an array of documents into Database:
app.get("/api/setupTodos", function (req, res) {
var nameModel = mongoose.model("nameModel", yourSchema);
//create an array of documents
var listDocuments= [
{
username: "test",
todo: "Buy milk",
isDone: true,
hasAttachment: false
},
{
username: "test",
todo: "Feed dog",
isDone: false,
hasAttachment: false
},
{
username: "test",
todo: "Learn Node",
isDone: false,
hasAttachment: false
}
];
nameModel.create(listDocuments, function (err, results) {
res.send(results);
});
'nameModel.create(listDocuments)' permit that create a collection with name of model and execute .save()
method for only document into array.
Alternatively, you can save one only document in this way:
var myModule= mongoose.model("nameModel", yourSchema);
var firstDocument = myModule({
name: String,
surname: String
});
firstDocument.save(function(err, result) {
if(if err) throw err;
res.send(result)
});
I prefer an easy example with pre-defined user values and validation checking model side.
// Create new user.
let newUser = {
username: req.body.username,
password: passwordHashed,
salt: salt,
authorisationKey: authCode
};
// From require('UserModel');
return ModelUser.create(newUser);
Then you should be using validators in the model class (Because this can be used in other locations, this will help reduce errors/speed up development)
// Save user but perform checks first.
gameScheme.post('pre', function(userObj, next) {
// Do some validation.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With