how to query a database using mongoose in node.js - node.js

I have written the following method that searches for a user in the database by their email.
/**
* Find a user by providing their email address
*/
DataProvider.prototype.findUserByEmail = function(callback, email) {
console.log("in findUserByEmail");
User.findOne({
emailAddress : email
}, function(error, user) {
if(error) {
console.log(error);
callback(error);
}
else {
console.log(user);
callback(user);
}
});
};
I'm trying to test it with the following:
function testFindUserByEmail() {
var expectedEmail = "user#user.com";
data.findUserByEmail(function(user) {
if (user.emailAddress === expectedEmail) {
console.log("User found");
} else {
console.log("User not found");
}
console.log(user);
}, "user#user.com");
console.log("test");
}
I get an outout of:
in findUserByEmail
test
It's like User.findOne() isn't getting called and I don't know why.
Other info:
var UserSchema = new Schema({
emailAddress : {
type : String
},
occupation : {
type : String
},
token : {
type : String
},
password : {
type : String
},
registrationDate : {
type : Date
},
activated : {
type : Boolean
}
});
/**
* Define Model
*/
var User = mongoose.model('User', UserSchema);
DataProvider = function() {
};

did you connected the database,
try: mongoose.connect('db-uri', function (err) {
next(err);
});

Related

How to use mongoose findAndUpdateOne()

i am trying to update mongoDB via mongoose using the findOneAndUpdate() method,
i destructure my fields from req.body but if i updated only a single value others are set to null, how do i fix that
CODE
const { name, email, phone, type } = req.body;
await Contact.findOneAndUpdate(
{ _id: req.params.id },
{ $set: { name, email, type, phone } },
{ upsert: true },
(err, updatedContact) => {
if (err) {
console.error(err.message);
res.status(400).send('Could not updat');
} else {
res.json(updatedContact);
}
}
);
});
******************************************
This gives me the desirable result i expected please not that i have not implemented error checking you can do that using the 'express-validator'
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, phone, type } = req.body;
// Build contact object
const updatedContact = {};
if (name) updatedContact.name = name;
if (email) updatedContact.email = email;
if (phone) updatedContact.phone = phone;
if (type) updatedContact.type = type;
try {
await Contact.findOneAndUpdate(
{ _id: req.params.id },
{ $set: updatedContact },
{ new: true }
);
res.json(updatedContact);
} catch (err) {
console.error(err.message);
res.status(400).send('Could not update');
}
});

atomic update ottoman couchbase & node js

I'm looking for a way to update multiple documents in a single request but according to ottoman git issues, atomic update is not supported. I have 2 models :
var Profile = ottoman.model('Profile', {
email : 'string',
firstname : 'string,
password : 'string,
Id : 'string'
};
var User = ottoman.model('User', {
creditCard : 'string',
userId : 'string'
};
This is my model
var user = {
update : (req, res) => {
var newEmail = req.body.email.trim();
var newPassword = req.body.email.trim();
User.find({userId : req.params.userId}, (err, user) => {
user.creditCard = 'XXXXXXXXXX';
user.save((err) => {
if(err){
//send error code
}
//logic here
//console.log(logic appears)
Profile.find({ Id : user.userId}, (err, profile) => {
profile.email = newEmail;
//logic here all skipped
profile.save((err) => {
if(err){
//send error
}
console.log(success);
})
});
});
});
}
};
and in my route :
router.post('/update', user.update);
Can anyone give me a clue to deal with updating 2 separates models. I'd be appreciated. thx

How to add new object by id to mongoDB collection?

I have a collection called Users which stores user's messages & info. I want to add new objects to existing collection by it's id.
I receive an error 'TypeError: user.insert is not a function' - i guess i missed something....
Here is the method from the controller :
UserDataController.prototype.sendMsg = function (userID, messages_data, cb) {
if (userID) {
user.findOne({_id: userID},function(err, result){ //Object id=59e5e542a5ba05056c57d847
// insert to the collection with the object id
user.insert({_id: userID} ,messages_data,function(err, result){
if(err) return cb(err);
return cb(null, result);
});
});
}
};
Here is the result i wish to get :
"sentmessages" : [{
"message_body" : "whatsup", // new object
"message_subject" : "whatsup",
"message_date" : "20/01/2017"
},
{
"message_body" : "whatsup", // new object
"message_subject" : "whatsup",
"message_date" : "20/01/2017"
}]
The schema looks like that :
var sentmessages = new schema({
message_date: String,
message_subject : String,
message_body : String,
});
var UserSchema = new schema({
firstname: String,
lastname: String,
email: String,
sentmessages :[sentmessages] // here is were i want to add new objects
});
Got it... needed to use $push
UserDataController.prototype.sendMsg = function (userID, messages_data, cb)
{
if (userID) {
var message_fixesd_data = messages_data.sent_messages[0];
user.update({_id: userID},
{ $push: { sent_messages: {
message_body : message_fixesd_data.message_body,
message_subject: message_fixesd_data.message_subject,
message_date : message_fixesd_data.message_date
}
}
}, function (err, result) {
if(err)
{
return cb(err);
}
else
{
return cb(true, 'File was save successfully', result);
}
});
}
};

Mongoose method to return id

I'm struggling to code a method in my mongoose model that returns only an id of a specific record.
This is my (simplified) schema:
var PersonaSchema = new Schema({
email: { type: String, unique: true },
personal_firstname: String,
created_at: { type: Date },
updated_at: { type: Date }
});
I would like to search for a record by email, than return the id if it exists. Currently I have this method setup as a static method, which does not work as suspected. It does not return the id, but the whole mongoose object.
PersonaSchema.statics = {
getPersonaId: function getPersonaId(email, cb) {
this.findOne({ email: email }).select("_id").exec(function(err, persona) {
if(err) {
throw err;
} else {
if(persona){
return persona._id;
} else {
return;
}
}
});
}
}
Any pointers are much appreciated.
EDIT: I was not quite clear in my question. What I want to do is get the persona id as a single value in my controller method.
Underneath I have a now working version, with a callback version. However, I would like it to be without a callback. So that I send an email to a static function, which returns the persona._id. How would I do that, without a callback?
var personaId = Persona.addPersonaId(personaData, function(err, persona, data) {
if(err){
console.log(err)
} else {
console.log(data);
}
});
You could have this in the model:
PersonaSchema.statics = {
getPersonaId: function (email, cb) {
this.findOne({ email: email }).select('_id').exec(cb);
}
};
And this somewhere else:
PersonaSchema.model.getPersonaId('test#test.com', function (err, persona) {
if (err) {
// handle error, express example:
return next(err);
}
// here you have
console.log(persona._id);
});
use callback instead of return.
.exec(function(err, persona) {
if(err) {
return cb( err, persona );
}
cb( null, {id: persona._id} );
});

How can I access app.locals within User model file?

I've created a file to hold some application wide configuration using app.locals. That config file looks like this:
config/vars.js
// App wide variables
module.exports = function (app) {
app.locals.accessLevels = [
{
"levelName" : "Basic",
"scrapes" : 3
},
{
"levelName" : "Pro",
"scrapes" : 10
},
{
"levelName" : "Ultimate",
"scrapes" : 99999
}
];
}
I want to access the app.locals.accessLevels array within my user's model which is here:
app/models/user.js
var userSchema = mongoose.Schema({
local : {
firstName : String,
lastName : String
// more stuff, simplified here for the question
}
});
userSchema.methods.remainingScrapes = function() {
// === >>> I need access to app.locals.accessLevels here
var today = new Date().yyyymmdd();
var scrapes = this.local.scrapes;
if (scrapes.length > 0) {
scrapes.forEach(function(item, i) {
if (today === item.date.yyyymmdd()) {
return item.count;
}
});
}
}
module.exports = mongoose.model('User', userSchema);
Then, there is also my existing code to consider where I'm accessing the User model (e.g. routes.js) because if I change something in the user model file, I don't want it to break my routes.js file...
** app/routes.js **
// I have simplified this file and removed excess code, but the function below
// is using the User model, so I have kept it in to demonstrate what code I have
var User = require('../app/models/user');
module.exports = function(app, passport) {
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) {
return next();
}
// automatically login admin
else if (app.locals.env == "development") {
User.findOne({ 'local.email' : 'anthony.hull#gmail.com' }, function (err, user) {
if (err) {
throw err;
} else {
console.log("login", "defaulting to admin user log in");
// assign user to req.user with passport's login method
req.login(user, function(err) {
if (err) {return next(err); }
return next(null, user);
});
}
});
}
else {
res.redirect('/login');
}
}
}

Resources