These are chat archives for Automattic/mongoose

7th
Dec 2016
Sean Ye
@nimysan
Dec 07 2016 03:32 UTC
hi I got a problem. I tried to connect to my local mongo db instance buy always keep connecting.
var db = mongoose.createConnection("mongodb://marryy:marryy123@10.237.72.171:27017/admin",{db:{username:"marryy","password":"marryy123"}});
console.log(db);
anyone can help? thank advance
Varun Jayaraman
@varunjayaraman
Dec 07 2016 03:38 UTC
can you paste the entire file
also i think the param should be user, not username if i remember correctly
one sec let me check docs
Sean Ye
@nimysan
Dec 07 2016 03:39 UTC
var mongoose = require('mongoose');
var db = mongoose.createConnection("mongodb://marryy:marryy123@10.237.72.170:27017/marryy");
console.log(db);
db.on('error', function(){
console.log("888888888888888888888");
});
db.on('connecting', function() {
// we're connected!
console.log("-------------------------------------------------------");
});
Varun Jayaraman
@varunjayaraman
Dec 07 2016 03:40 UTC
wrap it in 3 backticks man
have you used markdown before?
3 ticks on one line, your code, 3 ticks on the last line
my code here
Sean Ye
@nimysan
Dec 07 2016 03:40 UTC
mongoose.createConnection("mongodb://marryy:marryy123@10.237.72.170:27017/marryy");
console.log(db);
db.on('error', function(){
console.log("888888888888888888888");
});
db.on('connecting', function() {
// we're connected!
console.log("-------------------------------------------------------");
});
Varun Jayaraman
@varunjayaraman
Dec 07 2016 03:41 UTC
try using user instead of username
also what does db log out as
Sean Ye
@nimysan
Dec 07 2016 03:43 UTC
NativeConnection {
  base: 
   Mongoose {
     connections: [ [Object], [Circular] ],
     plugins: [],
     models: {},
     modelSchemas: {},
     options: { pluralization: true } },
  collections: {},
  models: {},
  replica: false,
  hosts: null,
  host: '10.237.72.170',
  port: 27017,
  user: undefined,
  pass: undefined,
  name: 'marryy',
  options: 
   { db: 
      { user: 'marryy',
        password: 'marryy123',
        read_preference: 'primary',
        forceServerObjectId: false,
        w: 1 },
     auth: {},
     server: { socketOptions: [Object], auto_reconnect: true },
     replset: { socketOptions: {} } },
  otherDbs: [],
  _readyState: 2,
  _closeCalled: false,
  _hasOpened: false,
  _listening: false,
  db: 
   Db {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     databaseName: 'marryy',
     serverConfig: 
      Server {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        _callBackStore: [Object],
        _commandsStore: [Object],
        auth: [Object],
        _dbStore: [Object],
        host: '10.237.72.170',
        port: 27017,
        options: [Object],
        internalMaster: false,
        connected: false,
        poolSize: 5,
        disableDriverBSONSizeCheck: false,
        _used: true,
        replicasetInstance: null,
        emitOpen: true,
        ssl: false,
        sslValidate: false,
        sslCA: null,
        sslCert: undefined,
        sslKey: undefined,
        sslPass: undefined,
        serverCapabilities: null,
        name: '10.237.72.170:27017',
        socketOptions: [Object],
        logger: [Object],
        eventHandlers: [Object],
        _serverState: 'connecting',
        _state: [Object],
        recordQueryStats: false,
        socketTimeoutMS: [Getter/Setter],
        db: [Circular],
        dbInstances: [Object],
        connectionPool: [Object] },
     options: 
      { user: 'marryy',
        password: 'marryy123',
        read_preference: 'primary',
        forceServerObjectId: false,
        w: 1 },
     _applicationClosed: false,
     slaveOk: false,
     bufferMaxEntries: -1,
     native_parser: undefined,
     bsonLib: 
      { Code: [Object],
        Symbol: [Object],
        BSON: [Object],
        DBRef: [Object],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Object],
        MinKey: [Object],
        MaxKey: [Object],
        promoteLongs: true },
     bson: BSON { promoteLongs: true },
     bson_deserializer: 
      { Code: [Object],
        Symbol: [Object],
        BSON: [Object],
        DBRef: [Object],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Object],
        MinKey: [Object],
        MaxKey: [Object],
        promoteLongs: true },
     bson_serializer: 
      { Code: [Object],
        Symbol: [Object],
        BSON: [Object],
        DBRef: [Object],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Object],
        MinKey: [Object],
        MaxKey: [Object],
        promoteLongs: true },
     _state: 'connecting',
     pkFactory: 
      { [Function: ObjectID]
        index: 16363752,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid],
        ObjectID: [Circular],
        ObjectId: [Circular] },
     forceServerObjectId: false,
     safe: false,
     notReplied: {},
     isInitializing: true,
     openCalled: true,
     commands: [],
     logger: 
      { error: [Function: error],
        log: [Function: log],
        debug: [Function: debug] },
     tag: 1481082166372,
     eventHandlers: 
      { error: [],
the key output I think is:
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
Varun Jayaraman
@varunjayaraman
Dec 07 2016 03:44 UTC
is mongod running?
Sean Ye
@nimysan
Dec 07 2016 03:45 UTC
yes, I can run in my java client.
package mongodb;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;

public class MongoDbConnectSample {

    public static void main(String[] args) {
        MongoClientURI url = new MongoClientURI("mongodb://marryy:marryy123@10.237.72.170:27017/marryy");
        MongoClient mongoClient = new MongoClient(url);
        System.out.println(mongoClient);
        MongoDatabase db = mongoClient.getDatabase("marryy");
        System.out.println(db.getWriteConcern());
        System.out.println(db.listCollectionNames().first());
        FindIterable<Document> find = db.getCollection("users").find();
        for (Document doc : find) {
            System.out.println(doc.toJson() + " -- " + doc.getString("loginId"));
        }
    }
}
INFO: Opened connection [connectionId{localValue:2, serverValue:169}] to 10.237.72.170:27017
system.indexes
{ "_id" : { "$oid" : "583d516e0c42455080d8fc86" }, "loginId" : "greatsan", "hashPassword" : "?r6?<\u001f1\u0019??7..??\u02b4<??K??\u0019\u0015?? ?wC\u0018", "salt" : "gen4UFuw5Z6kgE+16JYLosPng8sIInxyznU5KDgEbWGIcrWBkcTrxijbL0nw/8d6NxCsDhDUhuZguevnfYQBth0B+RY40QEJzGo/UsqECquyoGFBQ1ljIQ4fZeTRolNVkJ1RM9ELbtowlehse0QMqXiVHXgpmGrql5z4zUtJ2RI=", "date" : { "$date" : 1480413550923 }, "roles" : [], "payed" : false, "__v" : 0 } -- greatsan
Above is my java test case and the output.
run on same machine
Varun Jayaraman
@varunjayaraman
Dec 07 2016 03:46 UTC
what happens if you go into your cli
err... your terminal
and connect to mongo that way
Sean Ye
@nimysan
Dec 07 2016 03:47 UTC
I used the client tool Robomongo(0.8.4) and connected ok
{
  "name": "com.marryy",
  "version": "0.0.1-27",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "body-parser": "1.10.0",
    "connect-mongo": "^0.4.2",
    "cookie-parser": "1.3.3",
    "errorhandler": "1.3.0",
    "express": "4.10.4",
    "express-paginate": "0.0.5",
    "express-session": "1.9.3",
    "express-session-mongo": "^0.1.0",
    "jade": "*",
    "method-override": "2.3.0",
    "mongoose": "3.8.20",
    "mongoose-paginate": "3.1.3",
    "morgan": "1.5.0",
    "pbkdf2-compat": "^2.0.1",
    "promise": "^6.1.0",
    "serve-favicon": "2.1.7",
    "serve-static": "*",
    "solr-client": "^0.5.0",
    "upyun": "^1.1.2",
    "utils-merge": "1.0.0"
  },
  "subdomain": "marryy",
  "engines": {
    "node": "0.10.x"
  }
}
this is my package.json file. version problem?
Varun Jayaraman
@varunjayaraman
Dec 07 2016 03:49 UTC
lol idk
i use mongoose 4.6.5
i havent used 3.8.2 in a long time
what version of mongo are you using?
3.2?
Sean Ye
@nimysan
Dec 07 2016 03:51 UTC
mondod 2.4.14
maybe the version problem.
let me try new version

my operations been running find until this past weekend - and getting {"message":"connection 0 to 127.0.0.1:37000 timed out","name":"MongoError"}

it been working for 2 years, until all of a sudden; works fine in my local env - jsut not prod - both running mongoose 4.7.1

i had localhost before, jsut changed it to 127, seemed a bit better, but still ... connectiontimeout is default but increased reccountTries to 60 and poolSize is 60

any ideas ?

realisation
@realisation
Dec 07 2016 20:51 UTC
Hi guys, I'm having a problem trying to update properties of a mongoose object that is an object
how so? how are you attempting to do it?
realisation
@realisation
Dec 07 2016 20:57 UTC
I'm attaching the mongoose document onto the req object by calling app.param (Express), then in my route itself I'm _.forEaching over req.body, and doing req.center[key]=value;
the value from the foreach in this problem is an object with a few keys in it
however I just fixed it by supplying an additional forEach for nested values
why doesn't the prior work though? it's alright for arrays and strings probably numbers too
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:07 UTC
is req.center supposed to be the mongoose doc?
realisation
@realisation
Dec 07 2016 22:08 UTC
yeah, that's right
I have an app.param that queries the model with the center route parameter and attaches the result to req.center
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:08 UTC
can you give an example of what req.body looks like?
yep
i get that part
realisation
@realisation
Dec 07 2016 22:09 UTC
it's an object with keys that have value that are strings, an array or an object
the object property in this case has three keys that contain strings
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:09 UTC
ok so like
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3'
}
realisation
@realisation
Dec 07 2016 22:10 UTC
{ thing: { a: 1, b: 2, c:3 }, otherthing: "zebra"}
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:10 UTC
that's req.body
realisation
@realisation
Dec 07 2016 22:10 UTC
that's the deepest nested part of body
how'd you make it look like that?
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:10 UTC
yeah but forEach wont go deeper than the first level
wrap your code in 3 backticks
backticks has to be on a separate line
realisation
@realisation
Dec 07 2016 22:10 UTC
icic
yeah, I just used a second forEach
will probably refactor it into a recursive function
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:11 UTC
that seems like a poor design decision thoug
realisation
@realisation
Dec 07 2016 22:11 UTC
quite possibly
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:11 UTC
why dont you just declare the values you want to put on the mongoose doc
or you could do it like this
realisation
@realisation
Dec 07 2016 22:11 UTC
how do you mean? I have this one route that is receiving updates for a variety of properties
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:12 UTC
ok but it's always the same paths you want to set on req.center correct?
realisation
@realisation
Dec 07 2016 22:12 UTC
it's never one that isn't in the schema, right
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:13 UTC
so i meant make it more declarative like this
['data.time', 'data.duration', 'admin.readableId'].forEach(function(path) {
  req.center.set(path, req.body[path]);
});
if you do it that way the mongoose doc will also set the entire object on the field you're trying to
so if you have
{ nest1: { nest2: { nest3: 'frogsAreDope' } } }
let's suppose that's req.body
and req.center's Schema has a structure where the doc has a field that matches that structure
if you do req.center.set('data.nest1', req.body.nest1), it will set the entire object
realisation
@realisation
Dec 07 2016 22:17 UTC
nice, that's great to know
more readable too. I bet I could make a little function that grabs all the schema fields and makes that array too
Varun Jayaraman
@varunjayaraman
Dec 07 2016 22:20 UTC
yeah that's actually what i do
it's safer as well
allows you to sanitize what fields the user is allowed to set
but yeah i have a recursive function that maps allowed paths to values, and then does mongooseDoc.set(path, val)
lodash _.merge also won't work on mongoose docs so don't try that haha
creates reeeeeeally weird results
realisation
@realisation
Dec 07 2016 22:22 UTC
yeah that's definitely something I tinkered with :0