首页 > 解决方案 > 猫鼬 findById() 和 find({someparameter here}) 返回不同的数据吗?

问题描述

当我使用 findById. 我想制作蛞蝓,所以我使用了 mongoose-slug-generator。我曾经find从数据库中获取数据。

问题是我在使用方法时取回了数据,find但我无法将其作为 JavaScript 对象访问。

find 方法返回的数据

{
  category: [
    {
      subCategory: [Array],
      product: [Array],
      _id: 60e14e0994e27f3a2c93a26a,
      category: 'Electronics',
      image: 'images\\2021-07-04T05-58-33.034Z-download.jpg',
      createdAt: 2021-07-04T05:58:33.108Z,
      updatedAt: 2021-08-31T13:35:12.140Z,
      __v: 0
    }
  ],
  subCategory: [
    {
      category: [Array],
      product: [Array],
      _id: 60e14e2294e27f3a2c93a26c,
      subCategory: 'Laptop',
      createdAt: 2021-07-04T05:58:58.554Z,
      updatedAt: 2021-08-31T13:35:12.142Z,
      __v: 0
    }
  ],
  brand: [
    {
      product: [Array],
      _id: 60e14e6294e27f3a2c93a271,
      brand: 'sound',
      image: 'images\\2021-07-04T06-00-02.355Z-brand_4.png',
      createdAt: 2021-07-04T06:00:02.370Z,
      updatedAt: 2021-08-31T13:35:12.145Z,
      __v: 0
    }
  ],
  rating: [],
  sellCount: '0',
  color: [ 'blue' ],
  size: [ 'LG' ],
  image: [ 'images\\2021-08-31T13-35-12.116Z-hac-hdbw1231ra-z-a.png' ],
  _id: 612e3010abd51525286ea7e9,
  title: 'CCTV DAUHA HD 2.0 MP camera for security test2',
  description: 'THis is discription',
  price: 200,
  discount: 2,
  quantity: 200,
  feature: false,
  active: true,
  stock: true,
  createdAt: 2021-08-31T13:35:12.130Z,
  updatedAt: 2021-08-31T13:35:12.130Z,
  slug: 'cctv-dauha-hd-2-0-mp-camera-for-security-test2-rTfwYsVts',
  __v: 0
}

控制器


exports.getSingleProduct = (req, res, next) => {
  let slug = req.params.slug
  Product.find({slug: slug})
    .populate("category")
    .populate("subCategory")
    .populate("brand")
    .populate({
      path: 'rating',
      populate: {
        path: 'user',
        model: 'User'
      }
    })
    .then((product) => {
      console.log("controller" + product.title)
      let brandId =product.brand[0].id
      Product.find({ brand: brandId })
        .then((brand) => {
          res.render("user/single-product", {
            product,
            user: sessionUser,
            featured: req.featured,
            categories: req.categories,
            related: req.related,
            brand,
            bestSeller: req.bestSeller,
            banner: req.banner,
            mostRated: req.mostRated,
            storelists: req.storelists,
          });
        })
        .catch((err) => {
          console.log(err);
        })
    })
    .catch((err) => {
      console.log(err)
    })
}

代码以前可以工作但现在不工作

console.log("controller" + product.title)

曾经在使用 finById 方法时工作。

问题是什么?谢谢你

标签: node.jsjsonmongodbexpressmongoose

解决方案


推荐阅读