0

I've imported my Database from Firebase so I have few limitations in my schema. as My structure is like this

user: {

    ...other nodes

    pictures: { // this is an object, not an array
        autoId: {
            pictureUrl: "",
            pictureNumber: 1
        }
    }
}

I want to insert a picture with autoId in my pictures object. I found this and according to this I wrote my code like

 User.findOneAndUpdate({'_id': userId}, {$push:{pictures: {'pictureName': pictureName, 'pictureNumber': pictureNumber}}}, {new: true}, (err, user) => {
       // I am doing something here with user, no need to share
        });

but it gives me following error

{
    "errorCode": "INTERNAL_ERROR",
    "errorMessage": "The field 'pictures' must be an array but is of type object in document {_id: \"00Pag7qQiVbBIOw0zn0k6HWzeo22\"}"
}

Can anyone help me how to push object inside another object with autoId in mongoose?

piet.t
  • 11,718
  • 21
  • 43
  • 52
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36

1 Answers1

0
 var uniqueId = new mongoose.mongo.ObjectId();
    uniqueId = uniqueId.toString(); //Convert to string type
    var key = 'pictures.' + uniqueId; // if key is constant we can directly add that.

 User.findOneAndUpdate({'_id': userId}, {$set:{[key]: {'pictureName': pictureName, 'pictureNumber': pictureNumber}}}, {new: true}, (err, user) => {
       // Try using $set instead of $push as $push works on arrays
        });

You can find the documentation for the $set and go through it.

Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36
Vaibhav
  • 1,481
  • 13
  • 17