These are chat archives for Automattic/mongoose

6th
Feb 2018
Bikash Sharma
@bikashsharmabks
Feb 06 2018 06:57

Is Decimal type supported in latest mongoose https://docs.mongodb.com/manual/core/shell-types/#shell-type-decimal

I see https://github.com/Automattic/mongoose/blob/master/lib/types/decimal128.js in source code any example how to use it?

Kev
@lineus
Feb 06 2018 08:58
@bikashsharmabks here is a good article on it.
Bikash Sharma
@bikashsharmabks
Feb 06 2018 09:43
@lineus this for sharing this I think use of https://github.com/Vnkitaev/mongoose-float worked for my need
use of NumberDecimal stores the data as object in document like value 0.1234 is stored as NumberDecimal("0.1234")
using mongoose float stores are datatype double
Ambika Kumar
@ambikarajbadal
Feb 06 2018 10:46
Hey Folks! Can anyone help me that how can I develop a web app where anyone can create a group or join a group for teaching or learn facility...just like this website features.
ck12.org/my/groups
Chris Rutherford
@cjrutherford
Feb 06 2018 16:07

hey guys, working with JWT and having some trouble with my register route saving to the database. here's my code:

app.post('/register', (req, res) => {
    log.info('Checking password')
    if (req.body.password !== req.body.password2) {
        res.status(500).send({ success: false, message: "Passwords do not match" });
    } else {
        log.info('password verification successful');
    }
    const u = new User();
    //Parse the user from the body.
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(req.body.password, salt, (err, hash) => {
            const u = new User({
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                username: req.body.userName,
                password: hash,
                registeredApps: []
            });
            log.info(u.toString());
            u.save((err) => {
                if (err) {
                    log.error('error saving user to database.');
                    log.error(err);
                    res.status(400).send(err);
                } else {
                    log.info('user successfully saved.');
                    res.status(200).send({ success: true });
                }
            });
        });
    });
});

Anything immediately pop out as wrong here?

Karthik Iyengar
@karthikiyengar
Feb 06 2018 16:08
You missed handling the bcrypt’s err
Chris Rutherford
@cjrutherford
Feb 06 2018 16:09
that might do it
anything that might keep the model from being posted to the DB?
Karthik Iyengar
@karthikiyengar
Feb 06 2018 16:10
Unless you have model validators, I don’t see much
Chris Rutherford
@cjrutherford
Feb 06 2018 16:11
no errors are thrown in the hashing and salting. and not really doing anything with validation yet except in code. here's the model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

module.exports = mongoose.model('User', new Schema({
    firstName: String,
    lastName: String,
    username: String,
    password: String,
    registeredApps: [String]
}));
Karthik Iyengar
@karthikiyengar
Feb 06 2018 16:13
Not directly related but: const u = new User();
Why do you need this?
Do you get an error thrown by the save method?
Chris Rutherford
@cjrutherford
Feb 06 2018 16:14
thought it was a scope issue, so I defined the object outside the closure, and then used it inside the closure. it's redundant.
and no message from the save call.
Karthik Iyengar
@karthikiyengar
Feb 06 2018 16:15
I’m sorry, I don’t see anything else that’s obvious :-)
Chris Rutherford
@cjrutherford
Feb 06 2018 16:16
okay, thanks anyway @karthikiyengar this is the console output I get, and postman never gets a response:
[2018-02-06T16:15:16.147Z]  INFO: jwt-auth/112712 on AAWSDT2013028: Recieved a POST request from ::1 for /register.
[2018-02-06T16:15:16.148Z]  INFO: jwt-auth/112712 on AAWSDT2013028: Checking password
[2018-02-06T16:15:16.148Z]  INFO: jwt-auth/112712 on AAWSDT2013028: password verification successful
[2018-02-06T16:15:16.303Z]  INFO: jwt-auth/112712 on AAWSDT2013028:
  { registeredApps: [],
    _id: 5a79d494175b6cb849f5e7d6,
    firstName: 'Christopher',
    lastName: 'Rutherford',
    password: '$2a$10$dAaTkgf9pC4dWD6UTZuxN.4EGaXbHs5eh7j3bifyegkMCZjW1wRC.' }
Kev
@lineus
Feb 06 2018 16:18
have you tried adding the result to the save callback and printing that out?
u.save((err, result) => {
Chris Rutherford
@cjrutherford
Feb 06 2018 16:20
Thanks @lineus, but it gives the same output.....
Kev
@lineus
Feb 06 2018 16:21
you can try setting mongoose.set('debug', true)
Chris Rutherford
@cjrutherford
Feb 06 2018 16:27
it's as if the code is never run.....
Kev
@lineus
Feb 06 2018 16:34
#!/usr/bin/env node
'use strict'

const mongoose = require('../lib/test_db')
const bcrypt = require('bcrypt')

const User = mongoose.model('User', new mongoose.Schema({
  firstName: String,
  lastName: String,
  username: String,
  password: String,
  registeredApps: [String]
}))

bcrypt.genSalt(10, (err, salt) => {
  if (err) { return console.error(err) }
  bcrypt.hash('bibblewonkey', salt, (err, hash) => {
    if (err) { return console.error(err) }
    const u = new User({
      firstName: 'Kev',
      lastName: '!Kev',
      username: 'lineus',
      password: hash,
      registeredApps: []
    })
    u.save((err, result) => {
      if (err) { return console.error(err) }
      return console.dir(result)
    })
  })
})
results:
 _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
     firstName: 'Kev',
     lastName: '!Kev',
     username: 'lineus',
     password: '$2a$10$AFw8qGKyyz.olTNkBiihwOPAR5GTIMFzJWFE2Ca1lR/CPHvygtjJW',
     __v: 0 } }
that's on node 8.94 and mongoose 5.0.3 fwiw
data in the db:
> db.users.find('5a79d8c59e6a760860cfea0f').pretty()
{
    "_id" : ObjectId("5a79d8c59e6a760860cfea0f"),
    "registeredApps" : [ ],
    "firstName" : "Kev",
    "lastName" : "!Kev",
    "username" : "lineus",
    "password" : "$2a$10$AFw8qGKyyz.olTNkBiihwOPAR5GTIMFzJWFE2Ca1lR/CPHvygtjJW",
    "__v" : 0
}
Kev
@lineus
Feb 06 2018 16:40
@cjrutherford what version of mongoose and mongodb are you using? I'll setup a test env and try it out on the same versions.
Chris Rutherford
@cjrutherford
Feb 06 2018 16:43
it's mongoose 5.0.3 and mongodb 3.0.2
also as a note I'm using bcryptjs 2.4.3
Kev
@lineus
Feb 06 2018 16:47
I'll switch to that and try it before I switch DBs
bcryptjs didn't change my results, I'll switch to mongodb 3.02
Chris Rutherford
@cjrutherford
Feb 06 2018 16:49
kk, sound like a bug in mongoose?
Kev
@lineus
Feb 06 2018 16:51
can you copy my script and try running it on it's own? just to see if its some other piece of your puzzle that's causing it?
Chris Rutherford
@cjrutherford
Feb 06 2018 16:53
Thanks for your help, but I think I may have been a little dense.... I never called mongoose.connect......
Kev
@lineus
Feb 06 2018 16:54
I've done that before :)
Chris Rutherford
@cjrutherford
Feb 06 2018 16:54
it's saved now...... I just need to work out the hashing since the currently debugged code doesn't add it to the object.....
Kev
@lineus
Feb 06 2018 16:54
that was one of the reasons why I wrote my own wrapper that calls the connection etc and I just require it and it's done :)
Chris Rutherford
@cjrutherford
Feb 06 2018 16:55
@lineus :rocket: Thanks for the help again. I would def love to have that! I did the same for bunyan (all the log.info() calls go to bunyan)
Kev
@lineus
Feb 06 2018 16:56
const uri = 'mongodb://localhost:27017/'
const mongoose = require('mongoose')
mongoose.Promise = global.Promise

let mVer = mongoose.version
let mongoOpts

if (mVer.match(/^4/)) {
  mongoOpts = {
    useMongoClient: true
  }
} else {
  mongoOpts = {}
}

mongoose.connect(uri, mongoOpts)

module.exports = mongoose
then const mongoose = require('../lib/path_to_file')
Chris Rutherford
@cjrutherford
Feb 06 2018 16:59
nice! Thanks for this. going to write a gist for my logging wrapper if you would like. (rotating log files by default)
Kev
@lineus
Feb 06 2018 16:59
I'll have to check out bunyan, haven't heard of it :) this was fun! time for lunch :)
yeah, throw the link in here
Chris Rutherford
@cjrutherford
Feb 06 2018 17:00
const bunyan = require('bunyan');
const bFormat = require('bunyan-format');

var formatOut = bFormat({outputMode: 'long'});

const log = bunyan.createLogger({
  name: '<name of app>',
  streams: [{
    type: 'rotating-file',
    path: 'logs/access.log',
    period: '1w',
    count: 3
  },{
    stream: formatOut
  }],
  serializers: bunyan.stdSerializers,
  level: 'debug'
});

module.exports = log;
I liked it so much I genericized it, and made it a package
Kev
@lineus
Feb 06 2018 19:03
nice hehe :) when do the checks start rolling in?
Kev
@lineus
Feb 06 2018 19:20
fwiw, I would have chosen to use the wtfpl but I'm a pretty consistently sporting a neck beard.
hillct
@hillct
Feb 06 2018 19:27
Good afternoon all. Can someone clarify for me, why I can’t get a reference to the underlying mongoose instance from a Model as documented here http://mongoosejs.com/docs/api.html#Model ? using myModel.prototype.base;
Kev
@lineus
Feb 06 2018 19:32
can you paste a link to the relevant code where you're trying to access it @hillct ?
hillct
@hillct
Feb 06 2018 19:36
@lineus My code (model instance is Music) is var ObjectId = Music.prototype.base.Types.ObjectId; and the error I get is "Cannot read property 'Types' of undefined”. Clearly I’m calling something incorrectly… just not sure where I’m going wrong. Any thoughts?
Kev
@lineus
Feb 06 2018 19:37
ObjectId is in Schema
well, Schema.Types.ObjectId
hillct
@hillct
Feb 06 2018 19:38
var ObjectId = Music.prototype.Schema.Types.ObjectId; Thought I tried that, as I saw the same thing in the schema object. Trying it again...
Kev
@lineus
Feb 06 2018 19:39
do you have mongoose required at the top of your script?
you can just do mongoose.Schema.Types.ObjectId
hillct
@hillct
Feb 06 2018 19:41
@lineus no, which is why I want to extract the reference from my model, whih is required, and in turn requires mongoose
Kev
@lineus
Feb 06 2018 19:43
I'm pretty new at this, why not just require mongoose in that module?
hillct
@hillct
Feb 06 2018 19:43
@lineus still "Cannot read property 'Types' of undefined” now using var ObjectId = Music.prototype.Schema.Types.ObjectId;
@lineus memory usage… though Node should clean it up for me, but by definition, it shouldn’t be needed. It should be available by reference from th models
Kev
@lineus
Feb 06 2018 19:46
I'll poke around and see if I can find it
hillct
@hillct
Feb 06 2018 19:46
as a sanity check, I’m going to do this by requiring mongoose duplicately, but I’d really prefer not to have to...
Chris Rutherford
@cjrutherford
Feb 06 2018 20:30
@lineus if only there were checks in OSS for just delivering.... lol I did give you credit in the readme, so it gets your name out there lol
Kev
@lineus
Feb 06 2018 20:58
@hillct sorry man, I dug through the model and couldn't find what you're looking for. memwatch-next might make you feel better. it shows no size increase with multiple requires of the same module.
@cjrutherford I saw that :) thanks !