I created an api of route ‘/’ and when i should access this i should get all the products.
How i am using this to get data.Here is flow.
There is controllers folder, services folders and routes folder. From routes ‘/’ the controller getProducts() is called and then calling getProducts() there is a statement which calls getProducts() in services.js in services.js it tries to get data from mongo db data base but it is not returning any data. Can you please look the issue.
Here is controller code :
const productService = require('../services/productService')
const getAllProducts = async (req, res) => {
const allProducts = await productService.getAllProducts(body);
res.send({status:'ok',data:allProducts});
};
here is code in services.js
const Product = require('../database/models/ProductModel');
const mongoose = require('mongoose');
const getAllProducts = () => {
const p = Product.find({});
console.log(p)
return p;
};
And here is product Model
const mongoose = require('mongoose');
const productSchema = mongoose.Schema(
{
title:{
type:String,
required:[true,"Please enter a product name"]
},
},
{
timestamps: true
}
)
const Product = mongoose.model('Product',productSchema);
module.exports = Product;
When i use async and await in getProducts of services.js i get nothing in records but [] but when i do not use async and await and i use console.log to see what is there it prints something like this
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object], client: [MongoClient] },
Promise: [Function: Promise],
modelName: 'Product',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: [Object],
capped: false,
Promise: undefined,
'$wasForceClosed': undefined
},
name: 'products',
collectionName: 'products',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionOptions: [Object],
_connectionString: 'mongodb+srv://admin:somethinglikethis.mongodb.net/?retryWrites=true&w=majority',
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: 'ac-c0lqyqx-shard-00-00.wq6uzb8.mongodb.net',
port: 27017,
name: 'test'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Product },
schema: Schema {
obj: {
title: [Object],
description: [Object],
category: [Object],
quantity: [Object],
pictures: [Object],
owner: [Object]
},
paths: {
title: [SchemaString],
description: [SchemaString],
category: [SchemaString],
quantity: [SchemaString],
pictures: [SchemaString],
owner: [SchemaString],
_id: [ObjectId],
createdAt: [SchemaDate],
updatedAt: [SchemaDate],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: { initializeTimestamps: [Function (anonymous)] },
methodOptions: {},
statics: {},
tree: {
title: [Object],
description: [Object],
category: [Object],
quantity: [Object],
pictures: [Object],
owner: [Object],
_id: [Object],
createdAt: [Object],
updatedAt: [Function: Date],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: { timestamps: true },
options: {
timestamps: true,
typeKey: 'type',
id: true,
_id: true,
validateModifiedOnly: false,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: false,
strict: true,
pluralization: true
},
'$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
'$globalPluginsApplied': true
},
op: 'find',
options: {},
_conditions: {},
_fields: undefined,
_updateDoc: undefined,
_path: undefined,
_distinctDoc: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Product',
_closed: false,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'products'
},
_traceFunction: undefined,
'$useProjection': true
}
in this you can see products which is my collection there and i want to get all products in response but not getting. I am new to express and mongo can you spot the issue