Why isn’t Mongodb saving the data with default values declared in his schema?

Asked

Viewed 70 times

0

Greetings dev’s, I declared the schema as follows:

const mongoose = require('mongoose')

const TweetSchema = new mongoose.Schema({
    author: String,
    content: String,
    likes: {
        type: Number,
        default: 0
    },
    createdAt: {
        type: Date,
        default: Date.now // Pega a hora atual que a informação está sendo criada dentro do banco dedados
    }
})

// Exporta um modelo com o nome 'Tweet'
module.exports = mongoose.model('Tweet', TweetSchema)

The archive responsible for creating the document itself is this:

const Tweet = require('../models/Tweet')

module.exports = {
    async index(req, res) { // listagem de tweets ordenado pela data e tempo mais recente
        const tweets = await Tweet.find({}).sort('-createdAt')

        return res.json(tweets)
    },

    async store(req, res) { // criação de publicações
        const tweet = await Tweet.create(req.body)

        // Envia para todos conectados um evento chamado tweet, contendo as informações do tweet criado
        req.io.emit('tweet', tweet)

        return res.json(tweet)
    }
}

But when I do an Insert on my Collection so:

db.tweet.insert({ author: 'Matheus Wallace', content: 'Testando MongoDB'})

It does not enter a default value of both like, and date, why it will be ?

My connection to Mongo is being made like this:

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')

const app = express()

// Extrai o servidor http que foi criado com o express
const server = require('http').Server(app)

// Habilita o servidor para ouvir o protocolo HS (websocket e http)
const io = require('socket.io')(server)

mongoose.connect('mongodb://localhost/twetter-clone', {
    useNewUrlParser: true // Informa ao mongoose o novo formato de URL passado no parâmetro
})

app.use((req, res, next) => {
    // Passa a variável do io para nossa requisição
    req.io = io

    // Continua com o processamento do back-end
    return next()
})

app.use(cors())

// Faz o express utilizar o formato json para todas as requisições
app.use(express.json())

// Informa ao express para utilizar o arquivo routes para controlar as rotas da app
app.use(require('./routes'))

server.listen(3000, () => console.log('Server started on port 3000'))

NOTE: The version of Mongo that I am using is 3.6.10 and when I try to insert a data using a tool like Insomnia(PUT Method) without passing the default values it can record this data normally containing the default information, but if I give a find inside my DB the data I sent via PUT by Insomnia are not listed.

  • The schema is correct, try creating the data using the create method or else creating a new instance of the schema and then saving with save().

  • Ola @Justcase, I’m actually creating Collection with this command, but I refreshed Robo 3T and created this Collection with the name "tweets" containing all the default data in the correct way. What happened was that I was doing a test insert on a Collection with the singular name "tweet". I was just wondering what part of the code I’m creating an exact Collection with that plural name ?

  • I edited the above post containing the file I am creating at Collection

  • 1

    This is a pattern of Mongoose, it creates this way. Doc

No answers

Browser other questions tagged

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