Search code examples
javascriptnode.jsmongodbmongoosesave

Mongoose: save() is not a function when using find() and atributing value to variable


This is the basic structure of the Schema I am working with using mongoose:

  const User = {
    uid: {
      type: String
    },
    routes: {
      type: Array
    }
   }

In my application there is a POST to /route, in which uid and a new route are provided as "body parameters". In order to add to the routes array, I wrote a code similar to this (the only diference is that I check if the route already exists):

  var user = await User.find({uid: uid}) // user is found, as expected
  user[0].routes.push(route //parameter)  
  user.save()   

When a POST request is made, though, it throws an error:

TypeError: user.save is not a function

What am I doing wrong?


Solution

  • user in your code is an array of documents

    so you'll have mongo documents inside that array

    you can't do array.save, you've to do document.save

    await user[0].save()

    var user = await User.find({uid: uid}) // user is found, as expected
    if (user && user.length) {
        user[0].routes.push(route //parameter)  
        await user[0].save(); // save the 1st element of the object
    }
    

    if your query returns only 1 record better use https://mongoosejs.com/docs/api.html#model_Model.findOne

    var user = await User.findOne({uid: uid}) // user is found, as expected
    if (user) {
        user.routes.push(route //parameter)  
        await user.save(); // save the 1st element of the object
    }