简体   繁体   中英

Push objects to New Document with Mongoose and Express

Inside my model I have an array of objects. I need to insert objects to said array when creating a NEW document. I have found information on how to do it with findandupdate but I can't find how to do it with save().

This is my model:

const PettyCashItemsSchema = Schema (
  {
    pettyCashId:{
        type: Schema.Types.ObjectId,
        ref:'PettyCash',
        required: [true, 'La Caja Chica es Obligatoria']
    },
    item: {
        type: Number,
        unique: true
    },    
    items:[{
        concept: {
            type: String,
            maxlength:50,
            required: [true, 'El Concepto es obligatorio']
        },
        incomeAmount:{
            type: Number,
            maxlength:50,
            default:0,
            required: [true, 'El Ingreso es obligatorio']
        },
        expenseAmount:{
            type: Number,
            maxlength:50,
            default:0,
            required: [true, 'El Egreso es obligatorio']
        },
        description: {
            type: String,
            maxlength:50,
            required: [true, 'La Observación es obligatoria']
        },
        status: {
            type: Boolean,
            default: true,
            required: [true, 'El Estatus es obligatorio']
        }
    }],
  }  
);

And I am trying this way but it never saves anything in the array of objects:

        const pettyCashId= req.params.id;

        const itemToPush = {
            concept: req.body.concept,
            incomeAmount: req.body.incomeAmount,
            description: req.body.description,
            'createdBy':{
                uid: req.uid,
                username: req.user.username,
            }
        };
    
        const item = new PettyCashItems( { pettyCashId, $push: { 'items': itemToPush } } );

        await item.save();

        res.json ( item ); 

Thanks!

There is a syntax error.

You need to use an object to match the first condition

{"petryCashId":pettyCashId}

There is no problem with push

You don't need to use $push when creating a new document. You can simply set an array with a single document.

        const pettyCashId= req.params.id;

        const itemToPush = {
            concept: req.body.concept,
            incomeAmount: req.body.incomeAmount,
            description: req.body.description,
            'createdBy':{
                uid: req.uid,
                username: req.user.username,
            }
        };
    
        const item = new PettyCashItems({ 
             pettyCashId, 
             items: [itemToPush] 
        });

        await item.save();

        res.json ( item ); 

And when updating the document if you want to use .save method, you can use Array.push method for adding new item to items array although I will prefer to use findOneAndUpdate when updating the document. Below you can see an example when using .save when updating.

const pettyCashId= req.params.id;

const itemToUpdate = await PettyCashItems.findOne({ pettyCashId });

const itemToPush = {
    concept: req.body.concept,
    incomeAmount: req.body.incomeAmount,
    description: req.body.description,
    'createdBy':{
        uid: req.uid,
        username: req.user.username,
    }
 };

itemToUpdate.items.push(itemToPush)

await itemToUpdate.save();

res.json(itemToUpdate); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM