I am running a mongo query from the Order
database which aims to fetch the orders of a particular user by using his email-id. This is done using an API, but I am getting the complete object with some unnecessary details.
Code
I have written the following API in nextJS name myorders
import Order from "../../models/Order";
import connectDB from "../../middleware/mongoose";
import jsonwebtoken from "jsonwebtoken";
const handler = async(req, res) => {
const token = req.body.token;
const data = jsonwebtoken.verify(token,process.env.JWT_SECRET);
console.log(data)
let mere_orders = Order.find({email: data.email})
console.log("mereorders12 = ", mere_orders)
res.status(200).json({mere_orders});
}
export default connectDB(handler);
And console.log("mereorders12 = ", mere_orders)
gives me this
mereorders12 = Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: [Object],
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'orders',
collectionName: 'orders',
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,
_connectionString: 'mongodb://localhost:27017/chesswear',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: 'localhost',
port: 27017,
name: 'chesswear'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Order },
schema: Schema {
obj: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object]
},
paths: {
email: [SchemaString],
orderId: [SchemaString],
paymentInfo: [SchemaString],
products: [Mixed],
address: [SchemaString],
subtotal: [SchemaNumber],
status: [SchemaString],
_id: [ObjectId],
updatedAt: [SchemaDate],
createdAt: [SchemaDate],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: { initializeTimestamps: [Function (anonymous)] },
methodOptions: {},
statics: {},
tree: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object],
_id: [Object],
updatedAt: [Function: Date],
createdAt: [Object],
__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,
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
},
'$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
'$globalPluginsApplied': true,
_requiredpaths: [ 'status', 'subtotal', 'address', 'products', 'orderId', 'email' ]
},
op: 'find',
options: {},
_conditions: { email: '[email protected]' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: [Object],
name: 'orders',
collectionName: 'orders',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'orders'
},
_traceFunction: undefined,
'$useProjection': true
}
But I should return order like this
{
orders: [
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"[email protected]",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":4,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
}
,
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"[email protected]",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":14,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
}
]
}
Additionally this is the model schema of Order
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
email: { type: String, required: true },
orderId: { type: String, required: true },
paymentInfo: { type: String, default: "No payment info" },
products: { type: Object, required: true },
address: { type: String, required: true },
subtotal: { type: Number, required: true },
status: { type: String, required: true, default: "Pending" },
},
{ timestamps: true }
);
export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
Please help ??
CodePudding user response:
From Model.find()
, it returns Query
object.
Following the example, you need to execute the query asynchronously.
let mere_orders = await Order.find({email: data.email}).exec();
Or
let mere_orders = await Order.find({email: data.email});
As you are trying to return JSON as:
{
orders: [...]
}
You should return the response as below:
res.status(200).json({ orders: mere_orders });