如何使用mongoose

时间:2016-06-16 11:36:36

标签: arrays node.js mongodb express mongoose

我的问题是当我find() and print我的条目时,数组不显示。这是一个问题,因为我需要发送我的API。

我得到的结果是:

    {
      "_id": "576287e5a3536e670a39f3f2",
      "__v": 0,
      "products": [],
      "name": "SISI CEST ICI"
    },
    {
      "_id": "5762897e3032fe7c0a1d2408",
      "__v": 0,
      "products": [],
      "name": "hElo la mif"
    }

以下是我得到这个结果的方法:

  var response = {};
  mongoose.cat.find({},function(err,data){
   console.log(data);
 // Mongo command to fetch all data from collection.
     if(err) {
         response = {"error" : true,"message" : "Error fetching data"};
     } else {
         response = {"error" : false,"message" : data};
     }
     res.json(response);
 });

该模型如下所示:

var category = new mongoose.Schema({
    id: mongoose.Schema.ObjectId,
    name: { type: String, default: '' },
    products: [ {type : mongoose.Schema.ObjectId, ref : 'Product'} ]
});

var product = new mongoose.Schema({
    id: mongoose.Schema.ObjectId,
    name: { type: String, default: '' },
    price: { type: Number, default: '' }
});

var restoModel = mongoose.model('Resto', resto);
var MenuModel = mongoose.model('Menu', menu);
var CategoryModel = mongoose.model('Category', category);
var ProductModel = mongoose.model('Product', product);



module.exports = {
  resto: restoModel,
  menu: MenuModel,
  cat: CategoryModel,
  product: ProductModel
}

在我的数据库中,字段产品不为空,屏幕可以显示:

what i want to show

所以我的问题是:如何访问我的产品阵列中的数据?因为我需要他们把它寄回去。

我尝试了"Populate query",但没有提供任何内容。

我的问题是,如何以Json格式获取主要类别中的所有数据?

1 个答案:

答案 0 :(得分:0)

<强> // category.js

var mongoose = require('mongoose');

var CategorySchema = new mongoose.Schema({
    name: { type: String, default: '' },
    products: [{productID: {type : mongoose.Schema.Types.ObjectId, ref :      'Product'}}]
});

module.Category = mongoose.model("Category", CategorySchema);

<强> // product.js

var mongoose = require('mongoose');

var ProductSchema = new mongoose.Schema({
    name: { type: String, default: '' },
    price: { type: Number, default: 0 }
});

module.Product = mongoose.model("Product", ProductSchema);

//某个文件

var Product = require('./Product').Product,
    Category = require('./Category').Category;

var product = new Product({
    name: "Some name",
    price: 100
});

product.save(function(err){
    if(err) throw err;
});


*//creating*
var category = new Category({
    name: "Some name",
    products: [{
         productID: product._id
    },{
.....///and so on.....
    }]
});

*//saving*
category.save(function(error) {
    if (!error) {
        Category.find({})
            .populate('products.productID')
            .exec(function(error, cats) {
                console.log(JSON.stringify(cats, null, "\t"))
            })
    }
});

我希望它可以帮到你。