Save() method of Mongoose not saved

Asked

Viewed 230 times

0

I have the following problem:

When calling the Mongoose save method it seems to be doing nothing. The save code is as follows::

var newProjects = new projectModel({
    "teste":"teste"
});
newProjects.save(function (err){
    if(err){
        console.log("Erro");
        return;
    }else {
        console.log("Funcionou");
        return;
    };
});   
console.log("Passou")

What happens is that he never logs the "Error" or "Worked" messages, but logs the "Passed" message, and also does not create Collection in Mongodb. As this is the first time that the save of this model is executed, I believe that the creation should be done.

The Projectmodel variable is initialized thus:var projectModel = mongoose.model('Projects');

And the modeling of Collection is as follows:

var mongoose = require("mongoose");

var projectsSchema = new mongoose.Schema({
    teste: {type: String, required: true}
});

mongoose.model('Projects', projectsSchema);

Any idea what might be causing the problem?

  • I don’t know Mongoose directly, but by the code you posted here you’re not calling save itself, you’re setting the function that will be called when the save action is done. The "Passed" is appearing because it is in the same execution sequence as the definition of your save function. Take a look at the documentation of Mongoose and check when this save function is actually run.

  • Yes, she’s in the same running sequence, but I was hoping that before the "Passed" shows up, the "Bug" should be printed or the "Worked".

1 answer

0

You can use the method Model.create() where it creates a record in your database from its model:

try {
   const projectModel = await projectModel.create({teste:"teste"});
   return projectModel ;
}
catch(err) {
    return err
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.