Mongoose find query result always a null object - node.js

I'm desperately trying to solve my problem with "find" queries with mongoose in my app.
I begin to know very well the middleware, I used it on others apps and work well, but on a new project something goes wrong and it only finds null objects in my database...
//server/app.js
var db = require('./lib/database');
var User = require('./models/user');
//server/lib/database.js
var mongoose = require('mongoose');
var db = function () {
mongoose.connect('mongodb://localhost/pipeline');
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error'));
connection.once('open', function callback() {
console.log('connected'); //result : connected
});
};
module.exports = db();
//server/models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({ username: String, password: String });
module.exports = mongoose.model('User', userSchema);
Mongoose is well connected, there's no error in the console. So when mongoose is connected I use this method (I precisely use this in my LocalStrategy for PassportJS) :
User.findOne({username: "Paul"}, function (err, user){
console.log(user); // result : null
});
It's always null (and no error during the query), I also tested find({}) to check all entries, but the result is an empty array [].
Here's the User collection of my pipeline database (checked with Robomongo):
/* 0 */
{
"_id" : ObjectId("547649df8d99c22fa995b050"),
"username" : "Paul",
"password" : "test"
}
/* 1 */
{
"_id" : ObjectId("54765efdcd3b13c80c2d03e2"),
"username" : "Micka",
"password" : "lol"
}
Thank you for your help.

To have the 'User' model use the User collection, you need to explicitly provide that collection name as the third parameter to mongoose.model, otherwise Mongoose will use the pluralized, lower-cased model name which would be users.
module.exports = mongoose.model('User', userSchema, 'User');

Related

Update MongoDB with mongoose

I trying to update a field in users collection once a user is logged into the application. But the update query is not working at all.
users.js
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var jwt = require('jsonwebtoken');
router.post('/login', function(req,res,next){
let promise = User.findOne({email:req.body.email}).exec();
promise.then(function(doc){
if(doc) {
if(doc.isValid(req.body.password)){
// generate token
let token = jwt.sign({username:doc.username},'secret', {expiresIn : '3h'});
setOnlineStatus(doc.username);
} else {
return res.status(501).json({message:' Invalid Credentials'});
}
} else {
return res.status(501).json({message:'User email is not registered.'})
}
});
promise.catch(function(err){
return res.status(501).json({message:'Some internal error'});
})
})
function setOnlineStatus(username){
console.log(username); // log the correct username value
User.update(
{'username': username},
{$set: {'status':'Online'}},
);
}
Model - user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var schema = new Schema({
email : {type:String, require:true},
username: {type:String, require:true},
password:{type:String, require:true},
creation_dt:{type:Date, require:true}
});
schema.methods.isValid = function(hashedpassword){
return bcrypt.compareSync(hashedpassword, this.password);
}
module.exports = mongoose.model('User',schema);
So now the problem is once a request is send to /login service, the call to setOnlineStatus() is not updating users collection with a new field status having value 'online'.
NOTE: Using another service /register users are already added to the users collection.
I'm a newbie to express and mongodb. So please help me to solve this issue.
Thank you and answers will be appreciated.
you need to define status in the schema as mongoose will ignore it while updating other wise (read: option: strict)
try adding status: {type: String} to your schema
also the update() function returns a query (read: Model.update()) it doesn't update unless you pass a callback or execute it with .exec()
User.update({'username': username}, {$set: {'status':'Online'}}).exec()

Mongoose findById is returning null

So I have this schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TreeSchema = new Schema({
}, { collection: 'treeLocations' });
var TreeDetailsSchema = new Schema({
}, { collection: 'treeInfo' });
module.exports = mongoose.model('Tree', TreeSchema);
module.exports = mongoose.model('TreeDetail', TreeDetailsSchema, "treeInfo");
And I am calling by ID like this:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
router.route('/api/trees/:tree_id')
.get(function(req, res) {
TreeDetails.findById(req.params.tree_id, function(err, treedetail) {
if (err)
res.send(err);
res.json(treedetail);
});
});
For some reason - http://localhost:3000/api/trees/5498517ab68ca1ede0612d0a which is a real tree, is returning null
Something that might help you help me:
I was following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
The only thing I can think of that changed is that I have a collection name. Might that be it?
The step that I don't see is how you actually connect to MongoDB and after that, how you get the Model from the connection.
// connect to MongoDB
var db = mongoose.createConnection('mongodb://user:pass#host:port/database');
// now obtain the model through db, which is the MongoDB connection
TreeDetails = db.model('TreeDetails');
This last step is how you associate your model with the connected mongo database.
More info on Mongoose.model
There are several ways to establish a connection to MongoDB with mongoose, the tutorial uses:
mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o');
(Personally I prefer the more explicit mongoose.createConnection as shown in the example)
(I used mongoose 4.3.1 for this example)
My steps to reproduce, in order to provide a working example (without creating a webservice for it):
var mongoose = require('mongoose'),
TreeDetails, db;
// create the model schema
mongoose.model('TreeDetails', mongoose.Schema({
// .. your field definitions
}, {collection: 'treeInfo'}));
db = mongoose.createConnection('mongodb://user:pass#host/example');
TreeDetails = db.model('TreeDetails');
TreeDetails.findById('5671ac9217fb1730bb69e8bd', function(error, document) {
if (error) {
throw new Error(error);
}
console.log(document);
});
Instead of:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
try:
var mongoose = require('mongoose'),
TreeDetails = mongoose.model('TreeDetail');
Defining the collection name shouldn't give you any issues. It's just what the collection will be called in the database / when using the mongo shell.
And just to be sure, try logging req.params.tree_id before calling findById to make sure it's coming through as you suspect.

mongodb + mongoose: query not entering .find function

I am getting start with mongodb and mongoose but am having problems querying a database. There are a number of tutorials online for what I am trying to do but it just doesn't seem to work for me. My problem is that the .find() function is not even being called and the collection is not being displayed. I have a collection called Subjects in which I know there are some values (I manually entered them in the mongodb command line). I only tried including pertinent code but let me know if anything else is needed. Thanks in advance.
app.js file
require('./models/model.js');
var conn = mongoose.createConnection('mongodb://localhost/test');
var Subject = mongoose.model('Subjects');
Subject.find( { }, function (err, subjects) {
if(err) console.log("Error"); // There is no "Error"
console.log("Made it"); // There is no "Made it"
console.log(subjects);
});
model.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectsSchema = new Schema ({
subject: { type: String }
});
module.exports = mongoose.model('Subjects', SubjectsSchema);
Call mongoose.connect instead of mongoose.createConnnection to open the default connection pool that will be used by models created using mongoose.model:
mongoose.connect('mongodb://localhost/test');

node.js mongodb update error

I have a node.js website. I am using mongoose to connect with my mongodb. Adding new records works fine and find also works fine.
But when I update the record it throws the error below. I have a callback function but dont know whats wrong.
throw new Error("writeConcern requires callback")
^
Error: writeConcern requires callback
Below is my update code.
var newUser = new User();
newUser.update({ 'local.email' : emailID }, { 'local.resetkey': ResetHash }, { multi: false }, function (err, res) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
});
This is my schema...
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var safe = { w: "0" };
// define the schema for our user model
local : {
email : String,
password : String,
resetkey : String,
resetexpiry : String,
},
});
module.exports = mongoose.model('User', userSchema);
newUser is a document, but you are calling update as it is defined for the model and therefore getting a wrong argument in place of the callback
Try: User.update(... as in the mongoose API docs: Model.update(conditions, update, options, callback);
You show incomplete code for your schema.

mongoose find().all()

Windows 7 x64, node.js, mongoose from npm.
var sys = require('util');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:28960/test_mongoose');
var Schema = mongoose.Schema;
//Model
var UserSchema = new Schema({
username : String,
uid : String,
messaged_on : Date
});
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
// create a new user
var user = new User({
uid : '54321',
username : 'Bob',
messaged_on : Date.now()
});
user.save( function (err) {
if (err)
return;
console.log('Saved');
User.find().all(function(user) {
console.log('beep');
});
});
Connection to mongod accepted, database 'test_mongoose' created.
Console print 'Saved', but 'beep' not.
I am newbie in mongoose, but, what is a prolem? Why do User.find().add() not call function back (user)?
Sorry for my bad english.
Maybe is it normal?
You should be calling User.find(... instead of User.find().all(.... The all method invokes the $all operator which is only used when matching arrays.

Resources