Mongoose population:如何为模型创建Schema并填充它?

时间:2016-09-18 19:35:47

标签: node.js mongoose population

我试图创建一个模型favorites.js并用user.js和dishes.js填充它,所以如果用户只使用该菜的id发布了一个喜欢的菜,它也会存储用户和列表该用户的最爱。

以下是我到目前为止所做的事情: 注意:因为我是新手,所以我的代码可能会遇到比我想象的更多的问题。 请至少看看收藏夹模型和favRouter如何填充它们。提前谢谢..

models / favorites:

var mongoose = require('mongoose');
//var Dishes = require('../models/dishes');
var Schema = mongoose.Schema;
var timestamps = require('mongoose-timestamp');
mongoose.Promise = global.Promise;
// create schema 
var favSchema = new Schema({
    id: {
        type: String,
        required: true
    },
    createdBy: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    dishes: {
        type: Schema.ObjectId,
        ref: 'Dish'
    }
},{
    timestamps: true 
});

var Favorites = mongoose.model('favorites', favSchema);
module.exports= Favorites;

模型/菜:

// Dependencies
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var timestamps = require('mongoose-timestamp');
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
mongoose.Promise = global.Promise;
// create schema 
var commentSchema = new Schema({
    rating: {
        type: Number,
        min: 1,
        max: 5,
        required: true
    },
    comment: {
        type: String,
        required: true
    },
     postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
},{
    timestamps: true
});

var dishSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    image:{
        type: String,
        required: true,
    },
    category: {
        type: String,
        required: true,
    },
      label: String || '',
      price: Currency,
    description: {
        type: String,
        required: true
    },
    comments: [commentSchema]
},{
        timestamps: true 
});
dishSchema.path('price').get(function(num) {
  return (num/100);
});
dishSchema.path('price').set(function(num) {
  return (num )
});
// model
var Dishes = mongoose.model('Dish', dishSchema);
module.exports= Dishes;

modles /用户:

    // Dependencies
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var timestamps = require('mongoose-timestamp');
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
mongoose.Promise = global.Promise;
// create schema 
var commentSchema = new Schema({
    rating: {
        type: Number,
        min: 1,
        max: 5,
        required: true
    },
    comment: {
        type: String,
        required: true
    },
     postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
},{
    timestamps: true
});

var dishSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    image:{
        type: String,
        required: true,
    },
    category: {
        type: String,
        required: true,
    },
      label: String || '',
      price: Currency,
    description: {
        type: String,
        required: true
    },
    comments: [commentSchema]
},{
        timestamps: true 
});
dishSchema.path('price').get(function(num) {
  return (num/100);
});
dishSchema.path('price').set(function(num) {
  return (num )
});
// model
var Dishes = mongoose.model('Dish', dishSchema);
module.exports= Dishes;

路由器/ favRouter:

var express = require('express');
var bodyParser = require('body-parser');
var Verify = require('./verify');
var Favorites = require('../models/favorites');
var favRouter = express.Router();
favRouter.use(bodyParser.json());

favRouter.route('/')
.all(Verify.verifyOrdinaryUser)
.get(function(req, res, next){
    Favorites.find({})
    .populate(['createdBy', 'dishes'])
    .exec(function(err, fav) {
        if(err) throw err;
        res.json(fav);
    });
})
.post(function(req, res, next){
    Favorites.create(req.body,  function(err, fav){
        if(err) throw err;
        req.body.createdBy = req.decoded._doc._id;
            console.log('Created favorite dish!');

            res.json(fav);
    });
})
.delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
    Favorites.remove({}, function(err, resp){
        if (err) throw err;
        res.json(resp);
    });
});

favRouter.route('/:objectId ')
.all(Verify.verifyOrdinaryUser)
.get(function(req, res, next){
    Favorites.findById(req.params.objectId)
    .populate(['createdBy', 'dishes'])
    .exec(function(err, fav){
        if (err) throw err;
        res.json(fav);
    });
})
.put(function(req, res, next){
    Favorites.findByIdAndUpdate(req.params.objectId, {
        $set: req.body
    },{
        new: true
    }, function(err, fav){
        if (err) throw err;
        // Delete the recent comment then add the new one
        fav.id(req.params.objectId).remove();
        req.body.createdBy = req.decoded._doc._id;
        fav.push(req.body);

        fav.save(function(err, fav){
            if(err) throw err;

            console.log('Updated comments!');
            res.json(fav);
        });
    });
})
.delete(function(req, res, next){
    Favorites.findByIdAndRemove(req.params.objectId, function(err, fav){

        if (fav.id(req.params.objectId).postedBy != req.decoded._doc._id) {
        var err = new Error('You are not authorized to perform this operation!');
        err.status = 403;
        return next(err);
    }
        fav.id(req.params.objectId).remove();

        fav.save(function(err, resp){
            if(err) throw err;
            res.json(resp)
        })
    });
});

module.exports = favRouter;

路由器/ dishRouter:

        var express = require('express');
    var bodyParser = require('body-parser');
    var Verify = require('./verify');
    var Dishes = require('../models/dishes');
    var dishRouter = express.Router();
    dishRouter.use(bodyParser.json());

    dishRouter.route('/')
    .get(Verify.verifyOrdinaryUser, function(req, res, next){
        Dishes.find({})
        .populate('comments.postedBy')
        .exec(function(err, dish) {
            if(err) throw err;
            res.json(dish);
        });
    })
    .post(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
        Dishes.create(req.body, function(err, dish){
            if(err) throw err;
            console.log('Dish created!');
            var id = dish._id;
            res.writeHead(200, {
                'Content-Type': 'text/plain'
            });
            res.end('Added the dish with id: '+ id);
        });
    })
    .delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
        Dishes.remove({}, function(err, resp){
            if (err) throw err;
            res.json(resp);
        });
    });

    dishRouter.route('/:dishId')
    .get(Verify.verifyOrdinaryUser, function(req, res, next){
        Dishes.findById(req.params.dishId)
        .populate('comments.postedBy')
        .exec( function(err, dish){
            if (err) throw err;
            res.json(dish);
        })
    })
    .put(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
        Dishes.findByIdAndUpdate(req.params.dishId, {
            $set: req.body
        },{
            new: true
        }, function(err, dish){
            if(err) throw err;
            res.json(dish);
        })
    })
    .delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
        Dishes.findByIdAndRemove(req.params.dishId, function(err, resp){
            if(err) throw err;
            res.json(resp)
        });
    });

// Comments
dishRouter.route('/:dishId/comments')
.all(Verify.verifyOrdinaryUser)
    .get(function(req, res, next){
        Dishes.findById(req.params.dishId)
        .populate('comments.postedBy')
        .exec(function(err, dish) {
            if(err) throw err;
            res.json(dish.comments);
        });
    })

    .post(function(req, res, next){
        Dishes.findById(req.params.dishId, function(err, dish){
            if(err) throw err;
            req.body.postedBy = req.decoded._doc._id;
            dish.comments.push(req.body);
            dish.save(function(err, dish){
                if(err) throw err;
                console.log('Updated comments !');
                res.json(dish);
        });
    });
})
    .delete(Verify.verifyAdmin, function(req, res, next){
        Dishes.findById(req.params.dishId, function(err, dish){
            if (err) throw err;

            for (var i = (dish.comments.length -1); i>= 0; i--){
                dish.comments.id(dish.comments[i]._id).remove();
                }
                dish.save(function(err, dish){
                    if (err) throw err;

                    res.writeHead(200,{'Content-Type': 'text/plain'});
                    res.end('Deleted all comments');
                });
        });
    });

    dishRouter.route('/:dishId/comments/:commentId')
    .all(Verify.verifyOrdinaryUser)
    .get(function(req, res, next){
        Dishes.findById(req.params.dishId)
        .populate('comments.postedBy')
        .exec(function(err, dish){
            if (err) throw err;
            res.json(dish.comments.id(req.params.commentId));
        });
    })
    .put(function(req, res, next){
        Dishes.findById(req.params.dishId, function(err, dish){
            if (err) throw err;
            // Delete the recent comment then add the new one
            dish.comments.id(req.params.commentId).remove();
            req.body.postedBy = req.decoded._doc._id;
            dish.comments.push(req.body);


            dish.save(function(err, dish){
                if(err) throw err;

                console.log('Updated comments!');
                res.json(dish);
            });
        });
    })
    .delete(function(req, res, next){
        Dishes.findById(req.params.dishId, function(err, dish){

            if (dish.comments.id(req.params.commentId).postedBy != req.decoded._doc._id) {
            var err = new Error('You are not authorized to perform this operation!');
            err.status = 403;
            return next(err);
        }
            dish.comments.id(req.params.commentId).remove();

            dish.save(function(err, resp){
                if(err) throw err;
                res.json(resp)
            })
        });
    });

    module.exports = dishRouter;

请帮忙。 提前谢谢

0 个答案:

没有答案