Skip to content

Instantly share code, notes, and snippets.

@neilsonlima
Created June 27, 2019 13:21
Show Gist options
  • Save neilsonlima/3aeba6897317fda17610039ad3d7d8d8 to your computer and use it in GitHub Desktop.
Save neilsonlima/3aeba6897317fda17610039ad3d7d8d8 to your computer and use it in GitHub Desktop.
Nodejs e MongoDB
'use strict'
const Model = require('model')
const mongoose = require('mongoose')
const log = require('ololog').noLocate
mongoose.connect(
'mongodb://localhost/mydb',
{ useNewUrlParser: true, useCreateIndex: true },
function (err) {
if (err) throw err
}
)
let main = {
start(data) {
let { n: name, k: t } = data
let { x: final } = t
if (final) {
Model.findOne({ name: name }, (err, obj) => {
if (err) throw err
if (obj == null) {
let model = new Model()
model._id = new mongoose.Types.ObjectId()
model.name = name
model.t.push(t)
model.save(err => {
if (err) throw err
let id = model._id
log.info('Cadastrado: ', id)
})
} else {
obj.t.push(t)
Model.updateOne(
{ _id: obj.id },
{ $set: { t: obj.t } },
(err, doc) => {
if (err) throw err
log.info('Atualizado: ', obj.id, ' Name: ', name)
}
)
}
})
}
}
}
main.start()
const mongoose = require('mongoose')
const modelSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, index: true, required: true },
t: []
})
const Model = mongoose.model('Model', modelSchema)
module.exports = Model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment