mongodb 我如何使用mongoose中间件填充

0kjbasz6  于 2023-01-04  发布在  Go
关注(0)|答案(1)|浏览(110)
{
    cartItems: [
      {
        product: { type: mongoose.Schema.Types.ObjectId, ref: "product" },
        quantity: Number,
        color: String,
        price: Number,
      },
    ],
    totalPrice: Number,
    totalPriceAfterDiscount: Number,
    user: {
      type: mongoose.Schema.ObjectId,
      ref: "user",
    },
  },
  { timestamps: true }
);

// @desc query mongoose middleware to populate
CartSchema.pre(/find/, function (next) {
  this.populate("user");
  next();
});```

it throw this error

MissingSchemaError: Schema hasn't been registered for model "user".\nUse mongoose.model(name, schema)\n at Connection.model (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/connection.js:1236:13)\n at _getModelFromConn (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js:581:15)\n at addModelNamesToMap (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js:507:17)\n at getModelsMapForPopulate (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js:198:7)\n at populate (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/model.js:4679:21)\n at _populate (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/model.js:4639:5)\n at /home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/model.js:4616:5\n at promiseOrCallback (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/helpers/promiseOrCallback.js:11:14)\n at Mongoose._promiseOrCallback (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/index.js:1266:10)\n at Model.populate (/home/melewasy/projects/full-E-commerce/node_modules/mongoose/lib/model.js:4614:23)"

i tried this line instead of mongoose middleware
let x = await Cart.findById(cart._id).populate("user");
but5z9lq

but5z9lq1#

导入用户方案

const User = require("file_path")

并将其添加到populate方法中

let x = await Cart.findById(cart._id).populate("user", User);

相关问题