mongoose find().all() - node.js

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.

Related

mongoose query doesn't return the actual object

I have added a method to my mongoose scheme. When I create an instance, I can call that object but when I query for that object and try to call the same method, it returns exception.
User.js file:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String
surname: String
});
userSchema.methods.print = function() {
console.log(this.name, this.surname);
};
module.exports = mongoose.model('User', userSchema);
The following code works as expected:
const user = new User({});
user.print();
But when I query mongodb and try to call print on the method it returns exception:
User.findById(id, function(err,user){
// print is not a function
user.print();
});
I can't see where I'm making mistake,
And suggestions ?
Thanks.
It is because you haven't created an object of User.
Change module.exports = mongoose.model('User', userSchema); to let User = module.exports = mongoose.model('User', userSchema); in the User.js file and create an object of User before calling the print method, like:
let User = require('<path>/User.js'); where you need to update path with the actual path of the file.

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()

Nodejs undefined var when separate code in models [duplicate]

This question already has answers here:
Reference error on node.js while include file
(2 answers)
Closed 6 years ago.
I'm writting my first nodejs app, and i'm getting an error when i move a piece of code to an external js file. the code i'm trying to move is a mongodb schema declaration:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//--------------------users ------------
var usersSchema = new Schema({
email: String,
name: String,
phoneNumber: String,
BirthDate: Date,
loginpwd:String
});
var UserModel = mongoose.model('users', usersSchema);
I'm using filesystem module to load the external file:
fs.readdirSync(__dirname+'/models').forEach(function(filename){
if (~filename.indexOf('.js'))
require(__dirname+'/models/'+ filename);
console.log(filename+" added");
});
the following block does not work well when I separate the code, throwing an "undefined UserModel" error:
var userData = new UserModel({email : req.body.edtEmail,
name: req.body.edtName,
phoneNumber: req.body.edtPhoneNumber,
BirthDate: req.body.edtBirthDate,
loginpwd: req.body.edtSenha});
// save user data to database
userData.save(function(err, record){
if(err) throw err;
// session setting
req.session.userEmail = req.body.edtEmail;
req.session.name = req.body.edtName;
req.session.phoneNumber = req.body.edtPhoneNumber;
req.session.birthDate = req.body.edtBirthDate;
req.session.userId = record._id;
res.redirect('/dashboard');
});
the following code works well in both inline code or "in file" code:
app.get('/users/json', function(req, res){
mongoose.model('users').find(function(err, users){
res.send(users);
});
});
Am I doing something wrong when load external file ? or missing something ?
There is a build in system in nodeJs to load files.
I am not really sure what you want to do but in nodejs you would do something like this
//Lets say this file is called UserModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//-------------------- rest of you code ------------
var UserModel = mongoose.model('users', usersSchema);
module.exports = UserModel; //this is important
Than in a another file you could just load this
var UserModel = require('UserModel');
var bob = new UserModel({ ....
so you can work with your UserModel. Read maybe the docs about require
Also can use like:
in your schema file: (say directory "models/userModel.js")
...
mongoose.model('UserModel', usersSchema);
in controller or other file where you want to use: (say directory "controller/userController.js")
require('../models/userModel');// load user model
var mongoose = require('mongoose'),
UserModel = mongoose.model('UserModel'),
var userData = new UserModel({email : req.body.edtEmail, //rest of code...});
userData.save(function(err, record){ //rest of code ...
and can use for route like: (follow like as controller)
app.get('/users/json', function(req, res){
UserModel.find(function(err, users){
res.send(users);
});
});

Mongoose find query result always a null object

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');

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.

Resources