如何在猫鼬和Node.js中填充所有集合

时间:2018-07-19 12:07:13

标签: node.js mongodb express mongoose

假设我有2个简单的模式

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

const ProductSchema = new Schema({
    owner: { type: Schema.Types.ObjectId, ref: 'User' },
    curriculums: [{ type: Schema.Types.ObjectId, ref: 'Curriculum' }],
    title: { type: String },
    description: { type: String },
    price: { type: Number },
    created: { type: Date, default: Date.now }
})

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

const CurriculumSchema = new Schema({
    owner: { type: Schema.Types.ObjectId, ref: 'User' },
    product: { type: Schema.Types.ObjectId, ref: 'Product' },
    title: { type: String },
    description: { type: String },
    created: { type: Date, default: Date.now }
})

module.exports = mongoose.model('Curriculum', CurriculumSchema);

因此,我添加了一些课程,并且可以轻松地在数据库中查看所有课程。但是我想在获得一个产品时就将所有这些都填充。在发布诸如product.curriculum = req.body.curriculumId之类的产品时,我可以通过添加其ID轻松地仅填充一个集合,但是我想填充所有课程集合的数组,如下所示:

router.route('/products')
.get((req, res, next) => {
    Product.find( {  } )
        .populate('owner')
        .populate('curriculum')
        .exec()...

这是我保存课程的方式

const multer = require('multer');
const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'my-bucket',
        metadata: function(req, file, cb) {
            cb(null, { fieldName: file.fieldname });
        },
        key: function (req, file, cb) {
            cb(null, Date.now().toString())
          }
    })
});


router.post('/curriculums' ,upload.single('file'), (req, res, next) => {

    let curriculum = new Curriculum();

    curriculum.owner = req.decoded.user._id;
    curriculum.product = req.body.productId; // ?
    curriculum.title = req.body.title;
    curriculum.description = req.body.description;
    curriculum.file = req.file.location;

    curriculum.save()
         .then(res => console.log(res))
         .catch(err => console.log(err));

        res.status(201).json({
            sucess: true,
            message: 'created the curriculum'
        });
});

并添加了两个课程集:

/* 1 */
{
    "_id" : ObjectId("5b597014e9c78621050c6943"),
    "created" : ISODate("2018-07-26T06:54:12.064Z"),
    "owner" : ObjectId("5b4cef7e816cc330042c33cd"),
    "product" : ObjectId("5b504f1c7bb5684c6171ff15"),
    "title" : "product 1",
    "description" : "product 1 desc",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5b5970fb13009421f72f0ef7"),
    "created" : ISODate("2018-07-26T06:58:03.108Z"),
    "owner" : ObjectId("5b4cef7e816cc330042c33cd"),
    "product" : ObjectId("5b504f1c7bb5684c6171ff15"),
    "title" : "product 2",
    "description" : "product 2 desc",
    "__v" : 0
}

这就是我发布产品的方式

let product = new Product();
product.owner = req.decoded.user._id;
product.category = req.body.categoryId;
product.curriculum = req.body.curriculumId, // only one id, but need all of them
product.title = req.body.title;
product.description = req.body.description;
product.price = req.body.price;

如您所见,要填充课程表,我只能对一个课程表ID进行硬编码,以便与产品一起查看。

在发布产品时,有没有一种方法可以对一系列课程进行编码,而不是对一个课程ID进行编码? (req.body.curriculumId)

1 个答案:

答案 0 :(得分:0)

我错过了将课程表收集推到Product Schema中的课程表数组的事情。在进行多对一关系时,应将保存的内容推送到要填充的数组中