问题填充对象 ID 数组

问题描述 投票:0回答:1

我不知道为什么它不再起作用了。当我打印购物车中的所有书籍时,我得到:

{
  products: [ { quantity: 1, _id: new ObjectId('65c9bf8f9d8b1b868124bfa8') } ]
}

所以它没有被填充。

这是我的app.js:

app.get("/cart", async (req, res) => {
  if (req.isAuthenticated()) {
    const user = await User.findOne({ _id: req.user._id }).populate(
      "cart.products.product",
    );

    console.log(user.cart);

    res.render("cart", {
      user: user,
    });
  } else {
    res.redirect("/api/auth/login");
  }
});

这是我的用户架构:

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");

const userSchema = new mongoose.Schema({
  username: String,
  email: String,
  password: String,
  books: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  cart: {
    products: {
      type: [
        {
          product: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Book",
          },
          quantity: {
            type: Number,
            default: 0,
          },
        },
      ],
      default: [],
    },
  },
  phone_number: {
    type: String,
    default: "",
  },
  address: {
    type: String,
    default: "",
  },
});

userSchema.virtual("cart.totalProducts").get(function () {
  let totalBooks = 0;

  this.cart.products.forEach((product) => {
    totalBooks += product.quantity;
  });

  return totalBooks;
});

userSchema.virtual("cart.totalPrice").get(function () {
  if (this.cart == undefined || this.cart.products.length == 0) {
    return 0;
  }

  let totalPrice = 0;

  this.cart.products.forEach((product) => {
    totalPrice += product.product.price * product.quantity;
  });

  return totalPrice;
});

userSchema.plugin(passportLocalMongoose, {
  selectFields: "username email",
  errorMessages: {
    MissingPasswordError: "Please enter a password",
    MissingUsernameError: "Please enter a username",
  },
});

module.exports = mongoose.model("User", userSchema);

任何想法将不胜感激。

我尝试更改填充字段,但不知道它是否是正确的路径。

dsahdsidssaoidisoahdioasdiosaiodassadnjpasjdsiahdosahdsahidhasihdoias

node.js mongodb express mongoose mongoose-populate
1个回答
0
投票

怀疑

cart.products
的架构不正确。

尝试应用

cart
的架构,如下所示:

cart: {
  products: [
    {
      quantity: {
        type: Number,
        default: 0,
      },
      product: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Book",
      }
    }
  ]
}

并确保参考集合(

ref
)正确。

© www.soinside.com 2019 - 2024. All rights reserved.