简体   繁体   中英

Mongoose mixed Type object array, can findOneAndUpdate

I have a controller edit card which updates the fields of cardsArray object. cardsArray is mixed type object as fileds of each card object is different so i am storing mixed.type Althought pushing new card using addCard controller works perfectly But when edit card controller is called, it gives type error When edit Controlller is callled is gives following error: TypeError: Cannot read properties of null (reading 'cardsArray')

    // Schema
     const userSchema = new mongoose.Schema(
              {
                name: {
                  type: String,
                  required: true,
                },
                email: {
                  type: String,
                  required: true,
                },
                password: {
                  type: String,
                  required: true,
                },
            
                cardsArray: [{ type: mongoose.Schema.Types.Mixed }],
              }


        
        

);

    //__Mongodb Data
    
        {
          "_id": {
            "$oid": "63b43ab32fc8d3c100cafecc"
          },
          "name": "usern_name",
          "email": "pr****@gmail.com",
          "password": "$2b$12$3nwifHakrBu94BwLXAC4Nu16Kw0.xyW8vAIPTMSgY7cYttVklDIZq",
          "cardsArray": [
            {
              "title": "some_title",
              "category": "Bank",
              "cardHolder": "some_name",
              "cardNumber": "54545454",
              "expiry": "23/01",
              "cvv": "***",
              "logoIndex": 72,
              "isFavourite": false,
              "_id": {
                "$oid": "63b83cc77288d277ef359533"
              }
            }
          ],
          
          "loginIdsArray": [],
          "docsArray": [],
          "activitiesArray": [],
          "__v": 0
        }
    
    
    // Add Card Controller.js___
    
         addCard: async (req, res) => {
            console.log(req.body.data, req.body.user_id)
            // console.log('obj_id', newObjectId)
            req.body.data._id = newObjectId;
            try {
        
              const response = await UserDatabase.findOneAndUpdate(
                { _id: req.body.user_id },
                {
                  $push: {
                    // cardsArray: req.body.data,
                    cardsArray: { $each: [req.body.data] },
                  },
                },
                { returnOriginal: false }
              );
              res.status(200).send(response);
            } catch (error) {
              console.log(error)
              res.status(404).json({ message: error.message });
            }
          },
        
    // edit card controller.js 
 
editCard: async (req, res) => {
  const id = req.params.id;

  const { category, title, cardHolder, cardNumber, expiry, cvv, logoIndex, isFavourite } = req.body;
  console.log(req.params.id)

  try {
 

    const response = await UserDatabase.findOneAndUpdate(
      { _id: "63b43ab32fc8d3c100cafecc", 'cardsArray._id': "63b709fc69a1cfa6fccd645c" },
      {
        $set: {
          "cardsArray.$.title": req.body.title,
          "cardsArray.$.category": req.body.category,
          "cardsArray.$.cardHolder": req.body.cardHolder,
          "cardsArray.$.cardNumber": req.body.cardNumber,
          "cardsArray.$.expiry": req.body.expiry,
          "cardsArray.$.cvv": req.body.cvv,
          "cardsArray.$.logoIndex": req.body.logoIndex,
          "cardsArray.$.isFavourite": req.body.isFavourite
        }
      },
    );

    console.log(response)
    res.status(201).json(response.cardsArray);
  } catch (error) {
    console.log(error)
    res.status(404).json({ message: error.message });
  }
}
  

it means that there is no data matching the following _id and cardsArray._id i thinks so its fails to find the feild 'cardsArray._id',first try finding the value by just findOne

await UserDatabase.findOneAndUpdate(
  { _id: "63b43ab32fc8d3c100cafecc", 'cardsArray._id': "63b709fc69a1cfa6fccd645c" })

if your find doesn't work try below methord not sure but it may work you have to either find the id and loop through the cardsArray of use $in or $match

 await UserDatabase.findOneAndUpdate(
  { _id: "63b43ab32fc8d3c100cafecc", 'cardsArray':{$in:[ {_id:"63b709fc69a1cfa6fccd645c" }]})

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