Angular + MongoDB mongoose:组件无法识别对象属性

时间:2017-09-29 13:56:28

标签: mongodb angular mongoose

这是我在MLab中定义的产品文档的摘录:

 {
"_id": {
    "$oid": "596161e1734d1d25634366ce"
},
 "images": {
    "regular": [
        "Amana Electric Range in Stainless Steel-1.jpg",
        "Amana Electric Range in Stainless Steel-2.jpg",
        "Amana Electric Range in Stainless Steel-3.jpg",
        "Amana Electric Range in Stainless Steel-4.jpg",
        "Amana Electric Range in Stainless Steel-5.jpg"
    ]
   }
}

这是Mongoose中相应模型的摘录:

const ProductSchema = new Schema({
    images:{}
});

var Product = mongoose.model('Product', ProductSchema, 'product');
module.exports=Product;

这是我在Angular中的产品型号:

export class Product {
_id: string;  
images:{};
}

我可以在Angular模板中显示图像,如下所示:

 <div class="col-xs-4">
    <img src="..\assets\images\{{product.images.regular[0]}}"
       id="largeimage" class="text-center">
  </div>

我尝试使用上面模板中显示的相同构造访问组件中的相同图像:

ngOnInit() {
this.route.params.subscribe(params => {
  let id = params['id'];

  this.product = this.dataService.getProduct(id);

  this.mainImage = this.product.images.regular[0];
})
}

我收到错误:属性常规不存在。属性常规确实存在,如模板中所示,但由于某种原因,它在组件中不起作用。我相信它可能与我的模型定义有关:images {}。如何在Mongoose和Angular模型中正确建模图像对象?

1 个答案:

答案 0 :(得分:1)

您的mongoose架构期待一个空对象。如果您要查找类似于打字稿中any类型的内容,则可以使用mongoose.Schema.Types.Mixed

import * as mongoose from 'mongoose';

const ProductSchema = new mongoose.Schema({
    images: mongoose.Schema.Types.Mixed
});

const Product = mongoose.model('Product', ProductSchema, 'product');
module.exports = Product;

此外,在Angular的产品模型中,最佳做法是明确说明类型:

export class Product {
  _id: string;  
  images: any;
}