简体   繁体   中英

Unable to add new item to MongoDB array

I am using the below code to update an existing document in a collection.I would like to push anew item to an array.However script neither throws exception nor add anything to array.

Requesting an experts advise to solve the issue.

transportModel.findOne({ "name": req.body['providerName'], "contact.postalCode": parseInt(req.body['postalCode']) },function (err, doc) {
    if (err) {
        logger.error("Error while updating record : - " + err.message);                    
    } else if (doc === null) {
        logger.error("Error while updating record in transport details : - unable to update database");                   
    } else {

        doc.contact.addressLine1= req.body['addressLine1']
        doc.contact.addressLine2= req.body['addressLine2']

        //An array  in transportModel.
        //Add new items to array                  
        doc.vehicle.push({
                vehicleType:req.body['vehicleType'],                            
            })                                         
            doc.save()
    }                
});

try $push method:

transportModel.update(
    { ...your query here }, 
    { $push: { vehicle:{ vehicleType:req.body['vehicleType'] } } },
    done
);

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