Julio
Julio

Reputation: 355

Model.create() from Mongoose doesn´t save the Documents in my Collection

I have created a sigle app with a Schema and a Model to create a Collection and insert some Documents.

I have my todoModel.js file:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const todoSchema = new Schema({
username: String,
todo: String,
isDone: Boolean,
hasAttachment: Boolean
});
const Todos = mongoose.model("Todo", todoSchema);
module.exports = Todos;

Then I have created a setUpController.js file with a sample of my Documents. Then I create a Model and I pass my sample of Documents and my Schema. I create a response to send tje result in JSON. Everything good here, as I get the result in json when accessing to the route.

Here is the code:

        Todos.create(sampleTodos, (err, results) => {

        if (!err) {
            console.log("setupTodos sample CREATED!")
            res.send(results);
        }
        else {
            console.log(`Could not create the setupTodos Database sample, err: ${err}`);
        }
        });

My problem is that this Documents don´t get saved in the collection !! When I access to the database, nothing is there.

This is my app.js file:

mongoose.connect("mongodb://localhost:27017/nodeTodo")
.then(connection => {
    app.listen(port);
    
})
.catch(err => {
    console.log(`Could not establish Connection with err: ${err}`);
});

Could anyone help me please ?

Thank you

Upvotes: 0

Views: 1051

Answers (2)

Htet Arkar Hlaing
Htet Arkar Hlaing

Reputation: 69

Try creating an instance and making the respective function call of that instance. In your case, save the document after creating an instance and it works like a charm.

const newTodos = new Todos({
username: "username",
todo: "todos",
isDone: false,
hasAttachment: flase
});

const createdTodo = newTodos.save((err, todo) => {
if(err) {
throw(err);
}
else {
//do your staff
}
})

Upvotes: 1

Ori Guy
Ori Guy

Reputation: 109

after the collection is created you can use the function inserMany to insert also a single document the function receives an array of objects and automatically saves it to the given collection

example:

  Pet = new mongoose.model("pet",schemas.petSchema)
  Pet.insetMany([
    {
      //your document
    }])

it will save only one hardcoded document

I hope it was helpful

Upvotes: 1

Related Questions