I have this code that queries all the data under my feedback model
const result = await models.Feedback.findOne({
include: [{
association: models.Feedback.Point,
order: [["date_saved", "DESC"]],
// where: { version_id: { [Op.not]: null } },
include: [{
association: models.Point.Creator
}, {
association: models.Point.User,
}, {
association: models.Point.Comment,
}]
}, {
association: models.Feedback.Project,
where: { subscription_id: currentUser.subscription_id }
}, {
association: models.Feedback.User,
include: [{
association: models.ProjectTeam.User
}]
}],
where: { id },
});
console.log(result.get({plain:true})'
It gives me an error result.get is not a function. I don't know why I can't use the get function. But from my other query, i can use the get function. I don't know why this code give me an error.
EDIT:
The value of the result is
ep_tblfeedback {
dataValues:
{ id: 239,
proj_id: 20006,
title: 'sample',
status: 'Open',
date_saved: 2019-08-07T09:41:16.000Z,
title_trans: null,
Points: [ [ep_tblpoint] ],
Project:
ep_tblproject {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false },
Users:
[ [ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team] ] },
_previousDataValues:
{ id: 239,
proj_id: 20006,
title: 'sample',
status: 'Open',
date_saved: 2019-08-07T09:41:16.000Z,
title_trans: null,
Points: [ [ep_tblpoint] ],
Project:
ep_tblproject {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false },
Users:
[ [ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team],
[ep_tblproject_team] ] },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { id: 239 },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'ep_tblfeedbacks', singular: 'ep_tblfeedback' },
omitNull: false,
tableName: 'ep_tblfeedback',
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: [Object] },
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [ [Object], [Object], [Object] ],
includeNames: [ 'Points', 'Project', 'Users' ],
includeMap: { Points: [Object], Project: [Object], Users: [Object] },
includeValidated: true,
attributes:
[ 'id', 'proj_id', 'title', 'status', 'date_saved', 'title_trans' ],
raw: true },
isNewRecord: false,
Points:
[ ep_tblpoint {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
Creator: [ep_tblusers],
Users: [Array],
comments: [Array] } ],
Project:
ep_tblproject {
dataValues:
{ id: 20006,
proj_name: 'exactplace',
client_id: 291,
proj_nr: 'ep-01',
subscription_id: 1000,
status: 'Open' },
_previousDataValues:
{ id: 20006,
proj_name: 'exactplace',
client_id: 291,
proj_nr: 'ep-01',
subscription_id: 1000,
status: 'Open' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: [Object],
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
tableName: 'ep_tblproject',
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: undefined,
includeNames: undefined,
includeMap: undefined,
includeValidated: true,
raw: true,
attributes: undefined },
isNewRecord: false },
Users:
[ ep_tblproject_team {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
ep_tbluser: [ep_tblusers] },
ep_tblproject_team {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
ep_tbluser: [ep_tblusers] },
ep_tblproject_team {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
ep_tbluser: [ep_tblusers] },
ep_tblproject_team {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
ep_tbluser: [ep_tblusers] },
ep_tblproject_team {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
ep_tbluser: [ep_tblusers] },
ep_tblproject_team {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false,
ep_tbluser: [ep_tblusers] } ] }
If I use result.dataValues or result.get('field') works. But result.get({plain: true}) doesn't work. I want to use the latter because that's what I declared from my GraphQLObjectTypes and it would be a too much of work if i'll change all its functions.
I want to know what caused this error, to get it to work.
EDIT (2):
I discovered that from my front end, Apollo React causes the error. I don't know what is the logic to the error, but rearranging the fields does the trick.
export const FEEDBACK_QUERY = (id) => gql`
{
feedback (id: ${id}) {
id
title
proj_id
proj_name
clientname
date_saved
versions {
id
version_name
__typename #include(if: false)
}
points {
id
point_nr
version_name
time_approve
time_estimate
priority
team {
id
name
project_role
__typename #include(if: false)
}
instructions
inst_engtrans
status
deadline
creator
comments {
id
user_id
comments
date_commented
__typename #include(if: false)
}
ack
date
__typename #include(if: false)
}
team {
id
name
email
project_role
__typename #include(if: false)
}
__typename #include(if: false)
}
}
`;
Still don't know why rearranging the fields fixes it.
Another way of doing this is raw:true, nest:true :
const result = await models.Feedback.findOne({
include: [
...
],
where: {
...
},
raw : true ,
nest : true
});
set raw parameter as true or false.
without this parameters some queries may be get error.
in my app I set the {raw: true} in setting section.
I set to true or false when trying to join models
Related
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);
})
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}
});
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 })
...
}
I was following an Udemy course and I tried to push the experience field. when I did so I got the error. I checked if the field actually existed in the database and it did. there are no spelling mistakes either and I am not able to unshift the JSON object. I followed every step in the tutorial but he was able to do so in the video and I wasn't able to do it.
JSON I am trying to push at the experience field:
{ "title":"developer",
"company":"mangoo",
"location":"karaikal",
"from":"01-12-2018",
"current":"true",
"description":"developed android app for the firm"
}
router.put('/experience',[
auth,
[check('title','Title is empty').not().isEmpty(),
check('company',"Company name is empty").not().isEmpty(),
check('from','from date is empty').not().isEmpty()]],
async (req,res)=>{
const errors=validationResult(req)
if(!errors.isEmpty()){
return res.status(400).json({errors:errors.array()})
}
const {title,
company,
location,
from,
to,
current,
description
} = req.body
const newExp={
title,
company,
location,
from,
to,
current,
description
}
try {
const profile = Profile.findOne({user:req.user.id})
console.log(profile)
profile.experience.unshift(newExp)
await profile.save()
req.json(profile)
} catch (error) {
console.error(error.message);
res.status(500).json('server error')
}
})
the schema:
const mongoose=require('mongoose')
const ProfileSchema= new mongoose.Schema({
user:{
type: mongoose.Schema.Types.ObjectId,
ref:'user'
},
company:{
type:String
},
website:{
type:String
},
location:{
type:String
},
status:{
type:String,
required:true
},
skills:{
type:[String],
required:true
},
bio:{
type:String
},
gitid:{
type:String
},
experience:[
{
title:{
type:String,
required:true
},
company:{
type:String,
requiredt:true
},
location:{
type:String
},
from:{
type:Date,
required:true
},
to:{
type:Date,
default: Date.now
},
current:{
type:Boolean,
default:false
},
description:{
type:String
}
}
],
education:[
{
school:{
type:String,
require:true
},
degree:{
type:String,
required:true
},
fieldofstudy:{
type:String,
required:true
},
from:{
type:Date,
required:true
},
to:{
type:Date,
default: Date.now
},
current:{
type:Boolean,
default: false
},
description:{
type:String
}
}
],
social:{
youtube:{
type:String
},
twitter:{
type:String
},
facebook:{
type:String
},
linkedin:{
type:String
},
instagram:{
type:String
}
},
date:{
type:Date,
default:Date.now
}
})
module.exports=Profile=mongoose.model('profile',ProfileSchema)
console.log(profile):
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: 'profiles',
collectionName: 'profiles',
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: 'mern-shard-00-00-jakyl.mongodb.net',
port: 27017,
user: 'jaga',
pass: 'jaggu123',
db: [Db]
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { profile },
schema: Schema {
obj: {
user: [Object],
company: [Object],
website: [Object],
location: [Object],
status: [Object],
skills: [Object],
bio: [Object],
gitid: [Object],
experience: [Array],
education: [Array],
social: [Object],
date: [Object]
},
paths: {
user: [ObjectId],
company: [SchemaString],
website: [SchemaString],
location: [SchemaString],
status: [SchemaString],
skills: [SchemaArray],
bio: [SchemaString],
gitid: [SchemaString],
experience: [DocumentArrayPath],
education: [DocumentArrayPath],
'social.youtube': [SchemaString],
'social.twitter': [SchemaString],
'social.facebook': [SchemaString],
'social.linkedin': [SchemaString],
'social.instagram': [SchemaString],
date: [SchemaDate],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {
'skills.$': [SchemaString],
'experience.title': [SchemaString],
'experience.company': [SchemaString],
'experience.location': [SchemaString],
'experience.from': [SchemaDate],
'experience.to': [SchemaDate],
'experience.current': [SchemaBoolean],
'experience.description': [SchemaString],
'experience._id': [ObjectId],
'education.school': [SchemaString],
'education.degree': [SchemaString],
'education.fieldofstudy': [SchemaString],
'education.from': [SchemaDate],
'education.to': [SchemaDate],
'education.current': [SchemaBoolean],
'education.description': [SchemaString],
'education._id': [ObjectId]
},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: { social: true },
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
user: [Object],
company: [Object],
website: [Object],
location: [Object],
status: [Object],
skills: [Object],
bio: [Object],
gitid: [Object],
experience: [Array],
education: [Array],
social: [Object],
date: [Object],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [ [Object], [Object] ],
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: 'findOneAndUpdate',
options: {},
_conditions: { user: '5ebd21d78db2ec4370193636' },
_fields: undefined,
_update: { '$push': { experience: [Object] } },
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: NativeCollection {
collection: [Collection],
Promise: [Function: Promise],
_closed: false,
opts: [Object],
name: 'profiles',
collectionName: 'profiles',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'profiles'
},
_traceFunction: undefined,
'$useProjection': true
}
You forgett to add the await keyword:
const profile = await Profile.findOne({user:req.user.id})
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!