2016-06-16 111 views
1

我的問題是,當我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格式的所有數據從我的主類?

回答

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")) 
      }) 
    } 
}); 

我希望它可以幫助你。

+0

Category.find.populate顯示與Category.find()相同的數據 – Gabson