0
votes

I have Mongoose User schema like this but i wanna push items in an array into one of my object

Here is Schema example

const userSchema = new Schema({

  tokens:[{
    token: {
        type: String,
        requird: true
    }
  }],
  tradings: {
    buy: {
        data: {
            type: Array
        }
    },
    sell: {
        data: {
            type: Array
        }
    },
    total: {
        data: {
            type: Array
        }
    }
  }
})

i want to insert an object const obj = { trade: 234234, time: 345345 } into data into buy so after inserting it should look like:

"tradings": {
   "buy": {
      "data": [{ trade: 234234, time: 345345 }]
   },
   "sell": {
      "data": []
   },
   "total": {
      "data": []
   }
}

I am using a function to do it, following

Users.findOneAndUpdate(
    { _id : req.body.id },
    {
        tradings : {
            $push: {
                buy : req.body.obj
            }
        }
    },
    {
        new: true
    },
    function(error, doc){
        if(error){
            res.status(500).json({
                error: error
            })
        }else{
            res.status(201).json({
                message: req.body.data.id
            })
        }
    }
)

But nothing is inserted into the array

1

1 Answers

1
votes

Your tradings field has the structure:

tradings: {
  buy: {
    data: {
        type: Array
    }
  },
  ...
}

And you want to push item in the data, not buy. And also, $push has the form:

{ $push: { <field1>: <value1>, ... } }

So your update should be:

Users.findOneAndUpdate(
{ _id : req.body.id },
{
    $push: {"tradings.buy.data": req.body.obj}
},...