Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
Mongoose saves empty object but object is not empty - Nodejs

I'm trying to parse a CSV file (which can contain multiple entries) and store the data directly into my mongoose DB. My code seems to be parsing the data correctly because when I debug and quickwatch the "entity" and "temp" variable, I see the data entries from the CSV. However, when I go to store the objects in the DB, I see empty objects w/ only an autogenerated ID.

testCSVfile.csv

author, ownerName, authorID, contactInfo, published, summary
jon doe, bob, 321, jondoe@gmail, 03/17, testing testing testing

Here is my uploadCSV.js file

const mongoose = require("mongoose");
const passport = require("passport");
const csvtojson = require("csvtojson");
const router = require("express").Router();
const bookModel= mongoose.model("Book");
const async = require('async');

csvtojson()
        .fromFile("testCSVfile.csv")
        .then(csvData => {
            async.eachSeries(csvData,(data,callback) => {
                  let entity = {
                    author: data.author,
                    ownerName: data.ownerName,
                    authorID: data.authorID,
                    contactInfo: data.contactInfo,
                    published: data.published,
                    summary: data.summary
                    };


                    bookModel.create({entity}, function(err)
                    {
                        if(err) return callback(err);
                        return callback(null);    
                    })
               },
                (err) => {
                     if(err) console.log(err); 
                     console.log("books are successfully imported!!!");
                     console.log(entity);
                });            
});

Terminal Output

[
[0]   {
[0]     author: 'jon doe',
[0]     ownerName: 'bob',
[0]     authorID: '123',
[0]     contactInfo: 'jondoe@gmail',
[0]     published: '03/17',
[0]     summary: 'testing testing testing',
[0]   }

As of now, the CSV file is local but eventually, it will be from a user that is uploading it from the frontend. Even though the entity variable has the right data, it isn't saving properly. If someone could give me some advice that would be greatly appreciated!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You haven't defined schema for your mongoose model, so it will let you insert anything in the database as the schema is empty.

https://mongoosejs.com/docs/guide.html#strict

The strict option, (enabled by default), ensures that values passed to our model constructor that was not specified in our schema do not get saved to the db.

Create your mongoose schema for the model

https://mongoosejs.com/docs/guide.html#definition

const bookSchema = new mongoose.Schema({
    author: String,
    ownerName: String,
    // ........ rest of your model properties
});
const bookModel= mongoose.model("Book", bookSchema);

Change

bookModel.create({entity}, function(err)

to

bookModel.create(entity, function(err)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda