MongoDB find()给出了错误的对象?

nqwrtyyt  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(138)

我正在Order数据库中运行一个Mongo查询,目的是通过使用某个特定用户的电子邮件获取他的订单。这是通过一个API完成的,但我得到的是一个完整的对象,其中包含一些不必要的细节。

代码

我已经在nextJS中编写了以下API,名称为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);

console.log("mereorders12 = ", mere_orders)给出的结果是:

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: 'mohit6@test.com' },
  _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
}

但我应该这样回复顺序:

{  
  orders: [
    { 
      "_id":"62693ae3f7fd0b7d87c8eb9c"},
      "email":"mohit3@test.com",
      "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":"mohit3@test.com",
      "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
    }
  ]
}

此外,这是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);

请帮帮忙。

lf5gs5x2

lf5gs5x21#

Model.find()返回Query对象。
按照该示例,您需要异步执行查询。

let mere_orders = await Order.find({email: data.email}).exec();

或者

let mere_orders = await Order.find({email: data.email});

当您尝试将JSON返回为:

{
    orders: [...]
}

您应返回如下响应:

res.status(200).json({ orders: mere_orders });

相关问题