Mongodb findOne () not return value nodejs - javascript

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 })
...
}

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

How to user mongodb documents with requirements in different files. (Discord oauth2 + discord.js)

Before I start, let me say, this is going to be a long question.
So: I am trying to make a Discord Oauth2 application, and I have the login page, cookies, and everything set up. When a new user logs in with discord, it makes a new document with MongoDB. Here is my DiscordUser.js. (Model + Schema)
const { Message } = require('discord.js');
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
discordId: {type: String, required: true},
username: {type: String, required: true},
guilds: {type: Array, required: true},
prefix: {type: String, requried: false}
});
const DiscordUser = module.exports = mongoose.model('User', UserSchema);
And then in my DiscordStrategy file:
const DiscordStrategy = require("passport-discord").Strategy;
const passport = require("passport");
const DiscordUser = require('../models/DiscordUser');
const router = require('express').Router();
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser( async (id, done) => {
const user = await DiscordUser.findById(id);
if (user) done(null, user);
})
passport.use(new DiscordStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.CLIENT_REDIRECT,
scope: ['identify', 'guilds']
}, async (accessToken, refreshToken, profile, done) => {
try {
const user = await DiscordUser.findOne({ discordId: profile.id})
module.exports = user;
console.log(user);
if (user) {
user.guilds.forEach(guild => {
if (guild.owner === true) {
router.get(`/${guild.id}`, (req, res) => {
res.render("modules")
})
}
});
const updateUser = await DiscordUser.updateOne({
discordId: profile.id,
username: profile.username,
guilds: profile.guilds
})
user.update();
done(null, user, updateUser);
} else {
const newUser = await DiscordUser.create({
discordId: profile.id,
username: profile.username,
guilds: profile.guilds,
prefix: "?"
})
//Creating the routes for each server
newUser.guilds.forEach(guild => {
if (guild.owner === true) {
router.get(`/${guild.id}`, (req, res) => {
res.sendStatus(200);
})
}
});
const savedUser = await newUser.save();
done(null, savedUser);
}
}
catch(err) {
console.log(err);
done(err, null);
}
}));
module.exports = router;
And this works perfectly! But here is the catch: When I try to use this in my test.js (discord bot command file), I cannot access it. I am not good with mongodb. Every document I made with the DiscordStrategy file, it has the attribute discordId, and it sets that to the users ID when logging in with Oauth2. And I know I can access that by doing this in test.js:
const DiscordUser = require('../../../dashboard/models/DiscordUser');
const user = DiscordUser.findOne({ discordId: profile.id});
console.log(user);
The profile.id is the passport info is from DiscordStrategy.js. But the profile is not referenced here, so I cannot use that as a argument. So I can also do:
const DiscordUser = require('../../../dashboard/models/DiscordUser');
const user = DiscordUser.findOne({ discordId: message.author.id});
console.log(user);
That should, in theory, give me the same result. But here is what happens when I run that:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionCount: 0,
mongooseCollection: NativeCollection {
collection: null,
Promise: [Function: Promise],
_closed: false,
opts: {
schemaUserProvidedOptions: {},
capped: false,
autoCreate: undefined,
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: null prototype],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
plugins: [],
id: 0,
_listening: false
},
queue: [],
buffer: true,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { User },
schema: Schema {
obj: {
discordId: [Object],
username: [Object],
guilds: [Object],
prefix: [Object]
},
paths: {
discordId: [SchemaString],
username: [SchemaString],
guilds: [SchemaArray],
prefix: [SchemaString],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: { 'guilds.$': [Mixed] },
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
discordId: [Object],
username: [Object],
guilds: [Object],
prefix: [Object],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
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',
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: false,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true
},
op: 'findOne',
options: {},
_conditions: { discordId: '491738288328146947' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: NativeCollection {
collection: null,
Promise: [Function: Promise],
_closed: false,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [NativeConnection],
queue: [],
buffer: true,
emitter: [EventEmitter]
},
collectionName: 'users'
},
_traceFunction: undefined,
'$useProjection': true
}
If I console.log the user in my DiscordStrategy.js, it gives me my Id, my guilds, and everything. This only gives me the structure of the schema. If you want to see my code, here it is: https://github.com/johnmsweet/hal (I left out the /dashboard/database, and the .env for security)
So I am basically asking how can I get the data from DiscordStrategy to my discord bot command files? (data from mongodb)

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

Cannot read property 'unshift' of undefined while trying to unshift a json object

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

mLab : Find all users getting db object instead of records

My express application i'm using mLab database if I find only one record then its fine but when i'm going to find list of users from database its returning me something like this.
Query
let User = app.db.collection("User");
User.find((err, users) => {
if (err) { return err; }
if (users) {
return res.json({ users: users});
}
});
I'm getting response like
Readable {
pool: null,
server: null,
disconnectHandler: { s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] }, bson: {}, ns: 'hs-cloud.User', cmd: { find: 'hs-cloud.User',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined } }, options: { skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } }, topology: EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHearbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function] },
_eventsCount: 14,
_maxListeners: undefined,
s:
{ options: [Object],
callbacks: [Object],
logger: [Object],
state: 'connected',
reconnect: true,
reconnectTries: 30,
reconnectInterval: 1000,
emitError: true,
currentReconnectRetry: 30,
ismaster: [Object],
readPreferenceStrategies: undefined,
authProviders: [Object],
id: 3,
topologyId: -1,
tag: undefined,
disconnectHandler: [Object],
monitoring: false,
haInterval: 10000,
wireProtocolHandler: {},
Cursor: [Object],
bsonInstance: {},
inquireServerStateTimeout: null,
bson: {},
pool: [Object],
isMasterLatencyMS: 138,
inTopology: false,
serverDetails: [Object],
serverDescription: null,
topologyDescription: null },
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] }, cursorState: { cursorId: null,
cmd:
{ find: 'hs-cloud.User',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined }, callbacks: null, logger: { className: 'Cursor' }, _readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null }, readable: true, domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, s: { numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'hs-cloud.User',
cmd:
{ find: 'hs-cloud.User',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 14,
_maxListeners: undefined,
s: [Object],
hashedName: '1309e35791f04f1f4fc35d5e683e81d350dd04f4',
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
topologyOptions:
{ socketOptions: {},
auto_reconnect: true,
host: 'ds030829.mlab.com',
port: 30829,
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
disconnectHandler: [Object],
bson: {},
messageHandler: [Function],
wireProtocolHandler: {} },
promiseLibrary: [Function: Promise],
currentDoc: null }, timeout: false, sortValue: undefined
}
If I try to find single record its returning a record with match criteria
User.findOne({ username: 'abc123' }, (err, user) => {
if (err) { return next(err); }
if (!user) {
return next(null, false, {
message: "Incorrect username."
});
}
I have configure mongo connection like this way
return new Promise((resolve, reject) => {
MongoClient.connect('mongodb://<username>:<password>#ds033829.mlab.com:33829/my-cloud', (err, database) => {
let db = database;
if (err) {
return reject(err);
}
return resolve(db);
});
});
and this db i'm storing into my express app
like
app.db = db;
Any idea friends what i'm missing I see mLab docs there the query is same but though i'm getting something like this.
thank you.
it appears as though findOne() is returning a document, but find() is returning a cursor.
var cursor = User.find();
// Execute the each command, triggers for each document
cursor.forEach(function(doc) {
console.log(doc);
}, function(err) {
console.log(err);
});

Categories

Resources