Mongoose 连接两个集合 [英] Mongoose connect two collections

查看:84
本文介绍了Mongoose 连接两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品集合,另一个关于产品库存的重新定位.我正在寻找的是,当我拿到产品时,所有的补货日期和新库存都会出现,就像这样:

I have a collection of products, and another on the reposition of stock of the product. What I'm looking for is that when I get the products, all the replenishment dates and the new stock appear, something like this:

{
  "ok": true,
  "producto": {
    "repo": [
    {
            "_id": "5ac643ab88b5a132384f7758",
            "restock": 22,
            "date": "2018-03-04T03:00:00.000Z",
            "producto": "5ac6433588b5a132384f7757",
            "__v": 0
        },
        {
            "_id": "5ac6470079b67f39985ffe3c",
            "restock": 44,
            "date": "2018-04-04T03:00:00.000Z",
            "producto": "5ac6433588b5a132384f7757",
            "__v": 0
        }
    ],
    "_id": "5ac6433588b5a132384f7757",
    "nombre": "Vianda Vegetariana",
    "usuario": "5ac546f293e2b932a47b5f43",
    "createdAt": "2018-04-05T15:39:33.911Z",
    "updatedAt": "2018-04-05T15:39:33.911Z",
    "__v": 0
    }
}

但我只有这个:

{
    "ok": true,
    "producto": {
        "repo": [],
        "_id": "5ac6433588b5a132384f7757",
        "nombre": "Vianda Vegetariana",
        "usuario": "5ac546f293e2b932a47b5f43",
        "createdAt": "2018-04-05T15:39:33.911Z",
        "updatedAt": "2018-04-05T15:39:33.911Z",
        "__v": 0
    }
}

这是我的实际代码:

// repo schema

var repositorSchema = new Schema({
    restock: { type: Number, required: [true, 'El restock es necesario']},
    date: { type: Date, required: true },

    producto: { type: Schema.Types.ObjectId, ref: 'Producto'},
    usuario: { type: Schema.Types.ObjectId, ref: 'Usuario', required: true }
}, { timestamps: true } );

module.exports = mongoose.model('Repositor', repositorSchema);

//product schema

var productoSchema = new Schema({
    nombre: { type: String, required: [true, 'El nombre es necesario']},
    sku: { type: String, required: false },
    repo: [{ type: Schema.Types.ObjectId, ref: 'Repositor', required: true }],
    usuario: { type: Schema.Types.ObjectId, ref: 'Usuario', required: true }
}, { timestamps: true } );

module.exports = mongoose.model('Producto', productoSchema);

我的填充代码:

Producto.find({})
    .populate('repo')
    .exec(
        (err, productos)=> {
            if (err) {
                return res.status(500).json({
                    ok: false,
                    mensaje: 'Error cargando productos',
                    errors: err
                });
            }

            Producto.count({}, (err, conteo)=> {
                res.status(200).json({
                    ok: true,
                    total: conteo,
                    productos: productos
                });
            });
});

为什么不工作?两者应该如何填充?

Why not working? How should populate the two?

推荐答案

我是通过以下方式解决的.在创建股票的函数中,我查找相关产品并执行push:

I solved it in the following way. In the function to create the stock, I look for the related product and execute a push:

app.post('/', mdAuth.verifyToken, (req, res)=>{

    var body = req.body;

    var repo = new Repo ({
        restock: body.restock,
        date: body.date,
        producto: body.producto,
        usuario: req.usuario._id
    });

    repo.save( (err, repoGuardado)=>{
        if (err) {
            return res.status(400).json({
                ok: false,
                mensaje: 'Error al crear repo',
                errors: err
            });
        } 

        res.status(201).json({
            ok: true,
            repo: repoGuardado
        });

        /* actuializar repo en producto */
        var id = body.producto;

        Producto.findById( id, (err, producto)=> {

            if (err) {
                return res.status(500).json({
                    ok: false,
                    mensaje: 'Error al buscar producto',
                    errors: err
                });
            }

            if (!producto) {
                return res.status(400).json({
                    ok: false,
                    mensaje: 'No existe un producto con ese ID',
                    errors: { message: 'No existe un producto con ese ID' }
                });
            }

            producto.repo.push(repo);
            producto.save();


        }); /* end producto find */

    });
});

这篇关于Mongoose 连接两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆