【问题标题】:Mongoose connect two collectionsMongoose 连接两个集合
【发布时间】:2018-09-15 13:01:10
【问题描述】:

我有一个产品集合,另一个关于重新定位库存的产品。我正在寻找的是,当我收到产品时,所有的补货日期和新库存都会出现,如下所示:

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

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

【问题讨论】:

  • 我在另一个帖子上看到了你给我的消息,我有时间会尽快查看这个问题,我接下来的 24 小时有点忙,不知道我有多快我会尽快回复您
  • @rakan316 谢谢,非常好。我解决了但没有使用populate函数,下面添加答案。
  • 在您显示的输出中,repo 数组为空,问题不在于填充,您没有将项目正确添加到 repo 数组,编辑以添加用于添加项目的代码回购数组
  • 哦,没关系,对不起,我不知道你解决了它

标签: node.js mongoose mongoose-populate


【解决方案1】:

我通过以下方式解决了它。在创建库存的函数中,我查找相关产品并执行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 */

    });
});

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 2021-03-14
    • 1970-01-01
    • 2023-03-28
    • 2021-09-08
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    相关资源
    最近更新 更多