如何在mongoose中添加集合中的引用项

时间:2017-03-06 16:51:03

标签: node.js mongoose mongoose-schema

items.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_illustrations:[String],
    item_stock:Number,   //0 available 1 last 5 items 2 not available
    item_quantity_ordered:{type:Number,default:0},
    item_price:Number,
    item_img:String,
    no_of_likes:{type:Number,default:0}
},{ versionKey: false });

module.exports = mongoose.model('items',ItemSchema);

foodtruck.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');


var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:{type:Number,default:5},
    foodtruck_total_votes:{type:Number,default:0},
    foodtruck_tag:String,
    foodtruck_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });



module.exports = mongoose.model('foodtruck',FoodTruckSchema);

item_list_foodtruck.js

var addItem = function(req,res) {
    var foodtruck_id = req.body.foodtruck_id;
    var newItem = new item();
    var itemList=[];
    newItem.item_name = req.body.item_name;
    newItem.item_tag = req.body.item_tag;
    newItem.item_category = req.body.item_category;

    for (var key in req.body) {
        if (req.body.hasOwnProperty(key)) {
            if(key =='item_illustrations'){
                newItem.item_illustrations = req.body[key];
            }
        }
    }
    newItem.item_stock = req.body.item_status;
    newItem.item_price = req.body.item_price;


    if((foodtruck_id)&&(foodtruck_id.trim()!='')) {
        foodtruck.findById(foodtruck_id.trim(),function (err, foodtrucks) {
        if (err)
            res.json({
            status:'500',
            message:'There is no data available'
        });

            newItem.save();
            foodtrucks.item_list.push(newItem);
            foodtrucks.save();

        foodtruck.findById(foodtruck_id.trim()).populate('item_list').exec(function (err, foodtrucks) {
            if (err) res.json({
            status:'500',
            message:'There is no data available'
        });
        res.send({
            status:'200',
            message:'Review List',
            data:foodtrucks
        });
    });
    });
    }
    else {
        res.json({
            status:'404',
            message:'Please enter valid foodtruck id'
        });
    }

};

实际上项目 foodtruck 集合中引用的文档。这里项目被添加到items数组中,但不知何故他们没有在 foodtruck中更新他们的引用。 item_list

0 个答案:

没有答案