0

I want to save my array of car object to my user.cars field in mongoose.

My User Schema looks like this:

const UserSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    cars: [{
        type: Array,
        required: false
    }]
})

I'm saving user cars on cars endpoint like this:

router.route('/cars')
  .post(async function (req, res) {
    User.findById(req.user._id)
      .then((user, err) => {
        if (err) {
           return res.json({err})
        }
        if (user && user._id) {
           user.cars = req.body.cars 
           user.save(function (err) {
             if (err) {
                res.status(500)
                return res.json({
                   success: false,
                   message: err.message || 'Update failed'
                  })
             }
             ioServer.sockets.emit('update-users')
             res.status(200).json({
                success: true,
                message: 'User updated successfully'
             })
           })
        } else {
          return res.json({message: 'No user', success: false})
        }
      })
      .catch(err => console.log(err))
  })

My req.body log looks like:

{ cars: [
    {
        type: 'Sedan',
        make: 'BMW',
        model: '525i',
        [...]
    },
    {
        type: 'Coupe',
        make: 'Subaru',
        model: 'BRZ',
        [...]
    },
    {
        type: 'SUV',
        make: 'Toyota',
        model: 'Rav4',
        [...]
    }
    ]
}

This code works, but mongoose save data as a new array, so it looks like this:

{ user.cars: [
    [
        {car},
        {car},
        ...
    ]
]}

But I want to get user.cars as a array of objects instead of passing new array into cars.

Many thanks for help with find where I did a mistake in my code.

2
  • post your full code before user.cars = req.body.cars Commented Jun 12, 2018 at 10:22
  • I posted full endpoint code @Ashish Commented Jun 12, 2018 at 10:38

2 Answers 2

1

Actually, you do not need to find user and save it again instead you can use $push operator to set cars array...

router.route('/cars')
  .post(async function (req, res) {
    User.findOneAndUpdate({_id: req.user._id}, {$push: { cars: {$each: req.body.cars}}})
      .then((user, err) => {
        if (err) {
           return res.json({err})
        }
        res.status(200).json({
           success: true,
           message: 'User updated successfully'
        })
      })
      .catch(err => console.log(err))
  })
Sign up to request clarification or add additional context in comments.

Comments

0

In your model Schema you are defining type of cars as Array. That's why it is saving data like array structure.

cars: [{
        type: Array,
        required: false
    }]

Instead create a clear schema of fields:

    cars: [{
       type: String,
       make: String,
       model: String,
       ...
    }]

This would fix your data.

2 Comments

:Facepalm: Thanks! Works like a charm :)
@Robson Wecome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.