-1

In users.js:

var mongoose = require('mongoose');

var User = mongoose.model('user', {
  username: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
  },  
  tasks: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Tasks',
  }],
});
module.exports = User;

I then add a newUser named user1 and save to mongo.

The mongo doc looks like:

{ 
    "_id" : ObjectId("574fb94f6a1e7d1826c16058"),
    "username" :  "user1",
    "tasks" : [ ],
    "__v" :  0
}

then try to fetch the document and it works fine in this handler:

In handlerA.js:

var User = require('../models/users.js');

module.exports.getUser = function(req, res){
  User.findOne({username: "user1"}, function(err, data){
    if(err){
      console.log('getUser err', err);
      res.send('ERROR')
    } else {
      console.log('getUser fx success = ', err, data);
      res.send(data)
    }
  });
};

The result of the console.log:

getUser fx success = null { tasks: [], __v: 0, username: 'user1', _id: 574fb94f6a1e7d1826c16058 }


but same code fails in this other handler in a separate file.

In handlerB.js:

var User = require('../models/users.js');

module.exports.addStuff = function(req, res){
   User.findOne({username: "user1"}, function(err, data){
    if(err){
      console.log('addStuff err', err);
      res.send('ERROR')
    } else {
      console.log('addStuff fx success =', err, data);
      res.send(data)
    }
  });
};

The result of the console.log:

addStuff fx success null null

Tried....and Failed....

I also tried this other solution from this question: Mongoose query return null

Mongoose pluralizes model names so it's running find on the "blogposts" collection instead of "blogpost". That said, your query in the mongo shell is on the "blogmodel" collection. In that case:

var BlogModel = mongoose.Model("BlogModel", ..)

or pass the collection name as the third param:

var BlogModel = mongoose.model("BlogPost", schema, "blogmodel")

This solution results in handlerA.js returning a null document as well as handlerB.js.

Thanks for your time. Much appreciated.


ADDENDUM. I ran a find({}) under both the User and the Tasks models in handlerB.js The returned document IN BOTH cases is based on the Tasks model. see console.logs below for User.find({}) and Tasks.find({}) the err is the null value then the data.

How badly have I broken things? How can a Model.find return data that is not even in the model?

User.find({},funtion(err, data) ____________________
console.log of err  then data
null 
[ { subtasks: [],
    team: [ [Object] ],
    __v: 0,
    maintask: '1',
    _id: 574fce63d744cba421f750c1 
  },
  { subtasks: [],
    team: [ [Object] ],
    __v: 0,
    maintask: '2',
    _id: 574fce65d744cba421f750c2 
  }
]

Tasks.find({},function(err, data) ___________________ 
console.log of err then data
null 
[ { subtasks: [],
    team: [ [Object] ],
    __v: 0,
    maintask: '1',
    _id: 574fce63d744cba421f750c1 },
  { subtasks: [],
    team: [ [Object] ],
    __v: 0,
    maintask: '2',
    _id: 574fce65d744cba421f750c2 
  },
]

This is the Tasks model... tasks.js

var mongoose = require('mongoose');

var subtaskSchema = new mongoose.Schema({
   subtask: {
   type: String,
  },
  team: {
    type: Array,
    'defualt': [],
  },
  done: {
    type: Boolean,
    'defualt': false,
  },
});

var Tasks = mongoose.model('tasks', {
  maintask: {
    type: String,
  },
  subtasks: {
    type: [subtaskSchema],
  },
  team: {
    type: Array,
    'defualt': [],
  },
  done: {
    type: Boolean,
    'defualt': false,
  },
});

module.exports = Tasks;
Community
  • 1
  • 1
Tim K
  • 1
  • 3
  • 2
    How are you calling addStuff and getUser? – Tim Hysniu Jun 02 '16 at 05:45
  • var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // Database var mongoose = require('mongoose'); mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/taskmaster'); – Tim K Jun 02 '16 at 06:45
  • // Handle Requests var handleUsers = require('./server/services/handleUsers.js') app.post('/addUser', handleUsers.addUser); app.get('/getUser/:username', handleUsers.getUser); app.get('/getAllUsers', handleUsers.getAllUsers); – Tim K Jun 02 '16 at 06:46
  • var handleTasks = require('./server/services/handleTasks.js') app.post('/addTaskOwner', handleTasks.addTaskOwner); app.put('/addStuff', handleTasks.addStuff); – Tim K Jun 02 '16 at 06:48
  • I tried User.find({}, funtion(err, data){......} in handlerB (the one with issues) and the document that was returned was the tasks collection! so the mongo shell command db.tasks.find() returns the same thing as User.find({}...... – Tim K Jun 02 '16 at 06:56

1 Answers1

0

The mongoose docs suggest to define a model like so, did you try this?

var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
Rudi
  • 2,987
  • 1
  • 12
  • 18
  • Hello Rudi. Ty for help. Unfortunately, I don't think it solved my issue. I still return the Tasks model when User.find({}) in the handlerB.js. – Tim K Jun 02 '16 at 09:21
  • var userSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true, lowercase: true, }, }); module.exports = mongoose.model('User', userSchema); – Tim K Jun 02 '16 at 09:22
  • Maybe it's a step in the right direction.. I can't find anything about the way you create models/schemas. Same with `Tasks`, schemas definition should be an instance of `mongoose.Schema` – Rudi Jun 02 '16 at 10:59
  • I have tried creating the models per the doc example for both models. Still return the tasks for User.find({}) instead of the users. Regarding the way I wrote the models. I am basically writing the Schema "in line" and I think (hmmmm) it is just semantics - no real difference from doc example. I have seen this technique used elsewhere. – Tim K Jun 02 '16 at 18:24
  • If you know what you're doing ok, otherwise better stick to the docs :) The problem sounds weird. Did you double check that you `require` the correct model file and not accidentally require the tasks model twice? – Rudi Jun 03 '16 at 05:36