Select data from node object - node.js

I want to show email from object in node.
This is my route
// View users
router.get("/show", function (req, res, next) {
var query = {};
var options = {};
User.paginate(query, options).then(function (result) {
return res.render("../modules/users/views/userList", {
layout: 'cmsLayout',
users: result.docs,
page: parseInt(result.page),
pages: parseInt(result.pages)
});
});
});
and my handlebars
<h1>{{users}}</h1> // WORK
{ created: 2018-11-25T20:33:19.531Z, _id: 5bfb070fa18eb649e0b5ea97, firstname: 'Jxxxx', lastname: 'xxxx', email: 'xxxxx', password: 'xxxxxx', ipadress: '::1', provider: 'local', status: '1', secretToken: 'xxxxxx', __v: 0 }
<h1>{{users.email}}</h1> // WONT WORK
I know its really stupid question but i cant figure out how to show only email or only firstname...

Looks like you're using mongoose with mongoose-paginate. According to the docs, the parameter passed to paginate's callback (ie. result) should be an array. This can be confirmed by checking the return value of typeof result.docs. You might want to do this in your handlebars template:
{{#each users}}
<h1>{{this.email}}</h1>
{{/each}}

Related

How to remove a certain position from an array of objects that matches a value in Mongoose?

Is the first time I am working with backend (Mongoose, express, nodeJs). I have a collection of users in MongoDB.
I am sending the favoriteId from frontend and getting it in the backend. I want to delete the position of the array that matches with the favorite Id I am passing to the function.
I have tried several ways to remove the favorite using the $pull operator and the favoriteId but none work. So I don't know how to do it.
I would appreciate if someone could help me.
This is structure in MongoDB:
_id: new ObjectId("63"),
username: 'test1',
email: 'test1#gmail.com',
favorites: [
{
id: '25',
version: 'version3',
team: 'team1',
},
{
id: '27',
version: 'version2',
team: 'team4',
}```
This is my controller function:
```export const removeFavorite = async (req, res) => {
//Here I have the user Id 63
const userId = req.params.userId;
//here I have the favorite Id I Want to remove : 25
const favoriteId = req.body.params.id;
// Here I select the user in the collection
const deleteFavorite = await User.findOne({ _id: userId });
// Here I want to remove the favorite that matches with favoriteId (25)
res.status(200).json('ok');
};```
Try this:
User.update({ _id: userId }, { $pull: { 'favorites': { 'id': favoriteId } } });

MongoDB and Mongoose Abnormal behavior?

I apologize for the maybe trivial question. I am accessing mongo db to obtain information on a user, verify the password, and save some data in Redis if the validation was successful.
But I'm misbehaving (probably my mistake).
My simple backend is built in express 4.17.2, node 17.2.0, and redis4.0.1.
Server-side MongoDB on cloud MongoDB Atlas (Version 4.4.10) and RedisLab (Redis in cloud version 6.2.3).
Here are some code snippets:
app.post('/identity/login', (req, res) => {
let userHash = '';
let result = false;
const user = req.body;
userHash = crud.login(user.username);
userHash.then(h => {
result = bcrypt.compareSync(user.password, h.password);
console.log('All object ',h);
console.log('Access to roles array',h.roles);
let value = {name:h.name, surname:h.surname, roles:h.roles, username:h.username};
console.log('value', value);
client.set(h.password, JSON.stringify(value), { EX: 60, NX: true });
res.send(result);
});
});
Making the POST call to that endpoint, I get the following (unexpected) results, highlighted by the logs:
All object {
_id: new ObjectId("61d1d38d0f4bac12d8f504ee"),
username: 'jdoe',
password: '$2a$14$5GULZRmiN0DXQXMaLwQiEO9S/OlBll5U4ZwkBn2NYpju0VRDFUqVO',
name: 'John',
surname: 'Doe',
roles: [ 'Admin' ]
}
Access to roles array undefined
value { name: 'John', surname: 'Doe', roles: undefined, username: 'jdoe' }
As you can see, if I log h.roles I get that the array is not defined, while logging the whole object the array property 'roles' is correctly valued. So obviously, when I go to build the object to save in Redis (as h.roles), the array is not created.
Why? Could you please help me and say me what I am doing wrong? My mistake, a mongoose problem (see 6.4.1)?
Below, I show the code to access MongoDB:
const login = async (username) => {
connectDB();
let dbPwd;
const User = mongoose.model('Users', UserSchema);
return await User.findOne({ username: username }, 'password name surname roles username').exec();
}
Thanks so much!

Why is property of user object in mongoose showing as undefined?

This is my Schema:
var UserSchema = new Schema ({
username: String,
password: String,
nativeLanguage: {
type: String,
default: "English"
},
This route prints out the user object to the console.
router.get('/add', isLoggedIn, async (req, res) => {
const Users = await User.find({_id: req.params._id});
console.log(req.user);
res.render('add', {User});
});
What I am trying to do is render specific properties of the user on the add page, to test that I am first trying to access them in the console. Unfortunately User.nativeLanguage comes up as undefined and I don't know why.
User is the model, Users as you named it is the user record.
Lets suppose you export your model.
exports.User = UserSchema;
Then in your route you need.
var user = require('../userModel');
user.find({ _id: req.params._id }, (err, doc) => (
if (!err && doc){
res.render('add', { User: doc});
}
))
Also consider using findOne instead of find if you plan to get only one record.

Fetching from Model has not supply the defaults

In my app, I am fetching the data from /home -by home Model. the Model contains the defaults object. But while i fetch the data, I am not able to see the default object in the model.
here is my model :
define(['backbone'], function(Backbone){
"use strict";
socialApp = window.socialApp || {};
socialApp.homeModel = Backbone.Model.extend({
url: "/home",
defaults:{
"category":"Level-1"
}
});
return socialApp.homeModel;
});
here is my view.js :
socialApp.homeView = Backbone.Marionette.ItemView.extend({
tagName:'div',
initialize:function () {
var that = this;
this.model.fetch().done(function(data){
that.render(data) // i am fetching here
});
},
render: function (data) {
console.log(data) //there is no defaults object here...
this.$el.html(homeTemp(data));
}
});
What is wrong here? I am using Nodejs as a server.
here is the console what i am getting:
{
__v: 0
_id: "5416ce23fc0c41ec0f03f672"
email: "afzil#gmail.com"
firstName: "Mohamed"
lastName: "Afzil"
password: "afzil"
username: "afzil"
}
thanks in adavnce.
As i can see in promise 'done' callback you have only fetch results, not model.
please modify your initialize function to this:
initialize: function () {
var that = this;
this.model.fetch({
success: function(model){
that.render(model.toJSON());
}
});
}

Save mongoose document again after deleting it

I try to unit test my restify node.js-app using mocha and without mocking out the mongodb database. As some tests will alter the database, I'd like to reset its contents before each test.
In my tests I also need to access the mongoose documents I am creating. Thus I have to define them outside of the beforeEach hook (see the user document below).
However, it seems like it's not possible to save a document a second time after emptying the database.
Below is a minimal example I've come up with. The second test will fail in that case, because user won't get saved a second time. If I delete the first test, beforeEach only gets called once and everything works nicely.
Also if I define user inside the beforeEach hook, it works as well.
So my actual question: Is it possible to work around this issue and save a document a second time after deleting it? Or do you have any other idea on how I can reset the database inside the beforeEach hook? What's the proper way to have the same database setup before each test case?
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var should = require('should')
var flow = require('async')
var UserSchema = new Schema({
username: {type: String, required: true, unique: true},
password: {type: String, required: true},
name: {type: String, default: ''}
})
mongoose.model('User', UserSchema)
var User = mongoose.model('User')
describe('test mocha', function() {
var user = new User({
username: 'max',
password: 'asdf'
})
before(function(done) {
var options = {server: {socketOptions: {keepAlive: 1}}}
mongoose.connect('mongodb://localhost/unittest', options, done)
})
beforeEach(function(done) {
flow.series([
function(callback) {
User.collection.remove(callback)
}, function(callback) {
user.save(callback)
}
], function(err, res) {
done()
})
})
it('should pass', function(done) {
true.should.equal(true)
// also access some elements of user here
done()
})
it('should have a user', function(done) {
User.find().exec(function(err, res) {
res.should.not.be.empty
})
done()
})
after(function(done) {
mongoose.disconnect()
done()
})
})
I faced same problem,I generated a copy of the document to save. When need to save the document after deleting it I saved the copy, and it worked. Like
var user = new User({
username: 'max',
password: 'asdf'
});
var userCopy = new User({
username: 'max',
password: 'asdf'
});
And in test cases.
user.remove(callback)
}, function(callback) {
userCopy.save(callback){
// should.not.exist(err)
}
}
It might not be good solution ,but it worked for me.

Resources