Sequelize returning more fields than requested - javascript

I have this function,
module.exports.getDepartments = function () {
return new Promise(function (resolve, reject) {
sequelize.sync().then(function () {
Departments.findAll({
attributes: ['departmentId', 'departmentName']
}).then(function(data){
resolve(data);
}).catch(function(err) {
reject("Error: " + err);
})
});
}
)};
And when I console.log() the data, I get all records with all these weird fields!
Departments {
dataValues: { departmentId: 5, departmentName: '' },
_previousDataValues: { departmentId: 5, departmentName: '' },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [ 'departmentId', 'departmentName' ] },
__eagerlyLoadedAssociations: [],
isNewRecord: false }
Departments {
dataValues: { departmentId: 6, departmentName: 'TEST' },
_previousDataValues: { departmentId: 6, departmentName: 'TEST' },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [ 'departmentId', 'departmentName' ] },
__eagerlyLoadedAssociations: [],
isNewRecord: false }
I've had to shorten it by like 20 fields, but you get the idea. What's going on? This is preventing me from running res.render back on my server.js because it's expecting on departmentId and departmentName, but is getting way more.

You need to instruct Sequelize to return raw data. By default it creates instances on the row results.
Example:
Project.findAll({ where: { ... }, raw: true })

Related

How do I return all documents in mongodb collection?

I'm new to javascript and mongodb, and I'm trying to build a simple blog engine. I'm trying to return all of the blog posts within mongodb so that I can use that data to fill in a ejs template. I get the output I want with console.log, but when I try saving the function result to a variable, I get much more data than I need.
Here's the code:
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
title : String,
image: String,
body: String
});
const Model = mongoose.model;
const BlogPost = new Model('posts', BlogSchema);
BlogPost.find((err, posts) => {
console.log(posts);
});
This produces what I want in the log:
[
{
_id: new ObjectId("62ef1ea68a82d65948539324"),
title: 'Test Title',
picture: 'n/a',
body: 'this is the body of the test post'
},
{
_id: new ObjectId("62ef202670ad070b78e928a3"),
title: 'Test Title 2',
picture: 'n/a',
body: 'this is the body of the second test post'
}
]
However if I try this:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
title : String,
image: String,
body: String
});
const Model = mongoose.model;
const BlogPost = new Model('posts', BlogSchema);
var AllPosts = BlogPost.find((err, posts) => {
posts;
});
console.log(AllPosts);
I get this:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: null,
Promise: [Function: Promise],
modelName: 'posts',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: {},
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'posts',
collectionName: 'posts',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://localhost/blog',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise]
},
queue: [],
buffer: true,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { posts },
schema: Schema {
obj: {
title: [Function: String],
image: [Function: String],
body: [Function: String]
},
paths: {
title: [SchemaString],
image: [SchemaString],
body: [SchemaString],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
title: [Function: String],
image: [Function: String],
body: [Function: String],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true
},
op: 'find',
options: {},
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: null,
Promise: [Function: Promise],
modelName: 'posts',
_closed: false,
opts: [Object],
name: 'posts',
collectionName: 'posts',
conn: [NativeConnection],
queue: [],
buffer: true,
emitter: [EventEmitter]
},
collectionName: 'posts'
},
_traceFunction: undefined,
'$useProjection': true
}
What am I doing wrong?
Thank you!
You should rather go with async/await calls. Right now your AllPosts variable has Promise as value. Just change it into:
var AllPosts = await BlogPost.find({});
console.log(AllPosts);
var AllPosts = await BlogPost.find({})
/*OR*/
var AllPosts={};
BlogPost.find({}).then(data=>
{
AllPosts=data;
})
.catch(err=>
{
console.log(err);
})

Node.js issue with schema. user ID validation error

I am quite new to node.js express. I am having an issue with my registration form, I used a condition which checks my user id is already in the database or not. it used to work before. now no matter what different userID i give, it always shows me validation error messge. here is my controller code.
exports.registerTeacher=(req, res) => {
let userIDTaken = User.findOne(req.body.userid); //here i am searching for userID in collection
if (userIDTaken) { //my condition about if userID exists in collection
return res.status(400).json({
message: `userID is already taken.`, //showing the message
success: false
});
}
let emailTaken = User.findOne(req.body.email); //same condition for email
if (emailTaken) {
return res.status(400).json({
message: `email is already taken.`,
success: false
});
}
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
let profileImage = req.files.profileImage;
let uploadPath= `public/profile/${req.body.userid}.jpg`;
profileImage.mv( uploadPath, function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
const password = bcrypt.hashSync(req.body.userid, 12);
const product = new User({
name: req.body.name,
email: req.body.email,
role: "teacher",
userid:req.body.userid,
password:password,
profileImage: uploadPath
});
product
.save()
.then(result => {
//console.log(result);
res.status(201).json({
message: "Created Profile successfully",
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
this piece of code used to work 2 days back, I havent done anything with my db, I have deleted all the collections. And I havent change anything related to db. what should I do? and what did i do wrong
here is the console log of req.body.userid and userIDTaken inside the condition.
45451212
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
opts:
{ bufferCommands: true,
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined },
name: 'users',
collectionName: 'users',
conn:
NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
plugins: [],
_listening: false,
_connectionOptions: [Object],
name: 'student-portal',
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db] },
queue: [],
buffer: false,
emitter:
EventEmitter { _events: {}, _eventsCount: 0, _maxListeners: undefined } },
model: Model { users },
schema:
Schema {
obj:
{ name: [Object],
email: [Object],
role: [Object],
userid: [Object],
password: [Object],
profileImage: [Object] },
paths:
{ name: [SchemaString],
email: [SchemaString],
role: [SchemaString],
userid: [SchemaString],
password: [SchemaString],
profileImage: [SchemaString],
_id: [ObjectId],
updatedAt: [SchemaDate],
createdAt: [SchemaDate],
__v: [SchemaNumber] },
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: { initializeTimestamps: [Function] },
methodOptions: {},
statics: {},
tree:
{ name: [Object],
email: [Object],
role: [Object],
userid: [Object],
password: [Object],
profileImage: [Object],
_id: [Object],
updatedAt: [Function: Date],
createdAt: [Function: Date],
__v: [Function: Number],
id: [VirtualType] },
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
s: { hooks: [Kareem] },
_userProvidedOptions: { timestamps: true },
options:
{ timestamps: true,
typePojoToMixed: true,
typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
'$globalPluginsApplied': true },
op: 'findOne',
options: {},
_conditions: { userid: '45451212' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: [Collection],
Promise: [Function: Promise],
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter] },
collectionName: 'users' },
_traceFunction: undefined,
'$useProjection': true }
even when i command db.getCollection('users').find({userid: 45451212}) in my db command. it shows zero record, so it clearly isnt in the database.
my User Schema
const { Schema, model } = require("mongoose");
const UserSchema = new Schema(
{
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
role: {
type: String,
default: "student",
enum: ["student", "teacher", "parent","admin"]
},
userid: {
type: String,
required: true
},
password: {
type: String,
required: true
},
profileImage: {
type: String,
required: false
}
},
{ timestamps: true }
);
module.exports = model("users", UserSchema);
maybe you can rewrite your code using callbacks, e.g:
User.findOne(req.body.userid, function(err,resp){
if(resp){
return res.status(400).json({
message: `email is already taken.`,
success: false}
});

Mongodb findOne () not return value nodejs

I try to do some email verification after a user subscribes to my API, but when I do user.FindOne(token), the user is found but I not able to get the value of the user in the database. The return is a big ass array and I don't see which value to choose. my code:
ValidationFunction:
const User = require('../models/User');
const Token = require('../models/Token');
module.exports = function (req, res, next) {
const headToken = req.header('token');
const token = Token.findOne({ token: headToken })
if (!token) {
return res.status(400).send('We were unable to find a valid token. Your token my have expired.')
} else {
console.log(token);
}
try {
const user = User.findOne({ _id: token._userId})
if (!user) return res.status(400).send('We were unable to find a user for this token.');
if (user.isVerified) console.log('déja vérifié');;
// Verify and save the user
user.isVerified = true;
user.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
res.status(200).send("The account has been verified. Please log in.");
});
next();
} catch (err) {
res.status(400).send('Invalid Token');
}
}
if I do console.log(token._userId) or console.log(token._id) I got undefined but if I do console.log(token) I got this:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection: NativeCollection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
_closed: false,
opts: {
bufferCommands: true,
capped: false,
autoCreate: undefined,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'tokens',
collectionName: 'tokens',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
plugins: [],
id: 0,
_listening: false,
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
name: 'test',
host: 'cluster0-shard-00-01-1lzx5.mongodb.net',
port: xxxxx,
user: 'xxxx',
pass: 'xxxx',
db: [Db]
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Token },
schema: Schema {
obj: { _userId: [Object], token: [Object], createdAt: [Object] },
paths: {
_userId: [ObjectId],
token: [SchemaString],
createdAt: [SchemaDate],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
_userId: [Object],
token: [Object],
createdAt: [Object],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 2,
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typePojoToMixed: true,
typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true
},
op: 'findOne',
options: {},
_conditions: { token: '05bfd1ff19ef015934e04d2a8f21d37d' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: NativeCollection {
collection: [Collection],
Promise: [Function: Promise],
_closed: false,
opts: [Object],
name: 'tokens',
collectionName: 'tokens',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'tokens'
},
_traceFunction: undefined,
'$useProjection': true
}
findOne returns a promise, you need to wait for it resolve to read the values.
change your function into this:
module.exports = async function (req, res, next) {
const headToken = req.header('token');
const token = await Token.findOne({ token: headToken })
...
}

Convert a string representation of an array to a JS array

I am converintg a legacy database and it currently stores the user roles as a string that looks like this:
["ADMIN", "MANAGER", "USER"]
I need to be able to convert this to an array in my response i send from express.
I currently have:
userRouter.get('/getAllUsers', (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty())
return res.status(422).json(errors.array())
userService.getUsers()
.then(users => res.status(200).json({
exception: false,
payload: users.map(user => ({
...user,
params: JSON.parse(user.params)
}))
}));
})
but this is giving me an error:
Unhandled rejection TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at stringify (/mnt/c/Development/tendesign/lfc-v2/node_modules/express/lib/response.js:1119:12)
at ServerResponse.json (/mnt/c/Development/tendesign/lfc-v2/node_modules/express/lib/response.js:260:14)
at /mnt/c/Development/tendesign/lfc-v2/dist/routers/user.router.js:21:57
at tryCatcher (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:763:18)
at tryOnImmediate (timers.js:734:5)
at processImmediate (timers.js:716:5)
when I console.log(users) before processing, I get this:
[ user {
dataValues:
{ id: 706,
name: 'Sandra Will',
email: 'sandra#design.us',
params: '["ADMIN", "MANAGER", "USER"]',
active: '1' },
_previousDataValues:
{ id: 706,
name: 'Sandra Will',
email: 'sandra#design.us',
params: '["ADMIN", "MANAGER", "USER"]',
active: '1' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
sequelize: [Sequelize],
hooks: {},
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
user {
dataValues:
{ id: 710,
name: 'Tommy Craw',
email: 'thomas.craw#cargo.com',
params: '["ADMIN", "MANAGER", "USER"]',
active: '1' },
_previousDataValues:
{ id: 710,
name: 'Tommy Craw',
email: 'thomas.craw#cargo.com',
params: '["ADMIN", "MANAGER", "USER"]',
active: '1' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
sequelize: [Sequelize],
hooks: {},
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
user {
dataValues:
{ id: 711,
name: 'LeeAnne',
email: 'leeanne.craw#cargo.com',
params: '["ADMIN", "MANAGER", "USER"]',
active: '1' },
_previousDataValues:
{ id: 711,
name: 'LeeAnne',
email: 'leeanne.craw#cargo.com',
params: '["ADMIN", "MANAGER", "USER"]',
active: '1' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
Just parse it.
const dbStr = '["ADMIN", "MANAGER", "USER"]';
const array = JSON.parse(dbStr);
console.log(array)
Converting circular structure to JSON means that the parser is getting stuck in a loop because a property points to a parent object.

parse the Array and get the right data

I've an array which contains objects. I'm trying to access these objects in javascript but it throws up an error everytime.
Here's the array,
[ Provider {
dataValues:
{ uuid: 'abc123',
csgKey: 'aghzfmNzZ2FwaXIgICAoMSfCQyiAQhtZWRfc3VwcA',
naic: '61239',
name: 'Company',
enabled: true,
weight: 0,
createdAt: Invalid Date,
updatedAt: Invalid Date,
ApplicationVersions: [Object] },
_previousDataValues:
{ uuid: 'abc123',
csgKey: 'hzQ29tcGFueRiAgICAoMSfCQyiAQhtZWRfc3VwcA',
naic: '61239',
name: 'Company',
enabled: true,
weight: 0,
createdAt: Invalid Date,
updatedAt: Invalid Date,
ApplicationVersions: [Object] },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: true,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: [Object],
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: [Object],
omitNull: false,
classMethods: {},
sequelize: [Object],
uniqueKeys: [Object],
hasPrimaryKeys: true },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [Object],
includeNames: [Object],
includeMap: [Object],
includeValidated: true,
attributes: [Object],
raw: true },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false,
ApplicationVersions: [ [Object] ] } ]
Here's what i tried
console.log(provider.Provider.dataValues[0]);
and
console.log(provider.Provider.dataValues.name);
This array is inside a function
Provider.findAll({where: {enabled: 1},
include: [{
model: ApplicationVersion,
where: {'active': true},
}],
}).then(function(provider) {
console.log('success function');
console.log(provider);
// console.log(provider['Provider']['dataValues']['name']);
console.log(provider.Provider.dataValues[0]);
// console.log(provider.name);
});
That's why i used provider.Provider.dataValues.name
I'm getting an error saying that dataValues is undefined.
I want to access the name attribute inside the dataValues.
Any suggestion is helpful.
Thank you!

Categories

Resources