MongoDB - Mongoose query findOneAndUpdate() doesn't update/duplicates the DB












0















I am trying to save and update findOneAndUpdate() ({upsert: true} - creates the object if it doesn't exist) the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save/update it under the Child Schema in the database. How can I do this with nodejs and mongoose? Here is the code that I tried....



Folder - Models - Stock.js



const mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
const slug = require('slug')


const childSchemaData = new mongoose.Schema({
date: mongoose.Decimal128,
open: mongoose.Decimal128,
high: mongoose.Decimal128,
low: mongoose.Decimal128,
close: mongoose.Decimal128,
volume: mongoose.Decimal128
})

const parentSchemaSymbol = new mongoose.Schema({
symbol: {
type: String,
trim: true,
minlength: 2,
maxlength: 4,
required: 'Plese enter a valid symbol, min 2 characters and max 4'
},
// Array of subdocuments
data: [childSchemaData],
slug: String

});

//we have to PRE-save slug before save the parentSchemaSymbol into DB
parentSchemaSymbol.pre('save', function (next) {
if (!this.isModified('symbol')) {
next()//skip it
return//stop this function from running
}
this.slug = slug(this.symbol)
next()
//TODO make more resiliant soslug are unique
})

module.exports = mongoose.model('Stock', parentSchemaSymbol)


Controller - webApiController.js



const mongoose = require('mongoose')
const axios = require('axios')

require('../models/Stock')
const parentSchemaSymbol = mongoose.model('Stock')



mongoose.Promise = global.Promise // Tell Mongoose to use ES6 promises
// Connect to our Database and handle any bad connections
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
mongoose.connection.on('error', (err) => {
console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`)
})

exports.webApi = (req, res) => {
let curValue = req.params.symbol

axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${curValue}&outputsize=compact&apikey=TUVR`)
.then(response => {
return highLow = Object.keys(response.data['Time Series (Daily)']).map(date => {
return {
date: Date.parse(date),
open: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['1. open']) * 100) / 100,
high: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['2. high']) * 100) / 100,
low: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['3. low']) * 100) / 100,
close: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['4. close']) * 100) / 100,
volume: parseInt(response.data['Time Series (Daily)'][date]['5. volume'])
}
})

})
.then(_ => {

let curValueSchema = new parentSchemaSymbol()

curValueSchema.symbol = curValue
highLow.map(item => {
curValueSchema.data.push(item)
})
const query = { symbol: `${curValue.toUpperCase()}` }
const update = { $addToSet: { data: [curValueSchema.data] } }
const options = { upsert: true, new: true }
curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
console.log('Saved the symbol', doc)
return res.send(highLow)
}).catch(e => {
console.log(e)
})
})
.catch(error => {
console.log(error)
})
}


Here is the piece of code that I am looking to fix. The rest is working:



 let curValueSchema = new parentSchemaSymbol()

curValueSchema.symbol = curValue
highLow.map(item => {
curValueSchema.data.push(item)
})
const query = { symbol: `${curValue.toUpperCase()}` }
const update = curValueSchema
const options = { upsert: true, new: true }
curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
console.log('Saved the symbol', doc)
return res.send(highLow)
}).catch(e => {
console.log(e)
})


Here is the error I am getting



TypeError: curValueSchema.findOneAndUpdate is not a function
at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:55:22)
at process._tickCallback (internal/process/next_tick.js:178:7)


Here is the data = highLow



enter image description here



SOLUTION



Because Mongoose by default creates a new MongoDB ObjectId ( this hidden _id field) every time you pass it a Javascript Object to update the field of a document.



To go around you can tell Mongoose to not create a new ObjectId, by making sure your mongoose schema is as followed:



Folder - Models - Stock.js



const mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
const slug = require('slug')


const childSchemaData = new mongoose.Schema({
"_id": false,
date: mongoose.Decimal128,
open: mongoose.Decimal128,
high: mongoose.Decimal128,
low: mongoose.Decimal128,
close: mongoose.Decimal128,
volume: mongoose.Decimal128
})

const parentSchemaSymbol = new mongoose.Schema({
"_id": false,
symbol: {
type: String,
trim: true,
minlength: 2,
maxlength: 4,
required: 'Plese enter a valid symbol, min 2 characters and max 4'
},
// Array of subdocuments
data: [childSchemaData],
slug: String

});

//we have to PRE-save slug before save the parentSchemaSymbol into DB
parentSchemaSymbol.pre('save', function (next) {
if (!this.isModified('symbol')) {
next()//skip it
return//stop this function from running
}
this.slug = slug(this.symbol)
next()
//TODO make more resiliant soslug are unique
})

module.exports = mongoose.model('Stock', parentSchemaSymbol)


Controller - webApiController.js



let curValueSchema = new parentSchemaSymbol()

curValueSchema.symbol = curValue
highLow.map(item => {
curValueSchema.data.push(item)
})
const query = { symbol: `${curValue.toUpperCase()}` }
const update = curValueSchema
const options = { upsert: true, new: true }
parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc => {
console.log('Saved the symbol', doc)
return res.send(highLow)
}).catch(e => {
console.log(e)
})









share|improve this question





























    0















    I am trying to save and update findOneAndUpdate() ({upsert: true} - creates the object if it doesn't exist) the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save/update it under the Child Schema in the database. How can I do this with nodejs and mongoose? Here is the code that I tried....



    Folder - Models - Stock.js



    const mongoose = require('mongoose')
    mongoose.Promise = global.Promise
    mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
    const slug = require('slug')


    const childSchemaData = new mongoose.Schema({
    date: mongoose.Decimal128,
    open: mongoose.Decimal128,
    high: mongoose.Decimal128,
    low: mongoose.Decimal128,
    close: mongoose.Decimal128,
    volume: mongoose.Decimal128
    })

    const parentSchemaSymbol = new mongoose.Schema({
    symbol: {
    type: String,
    trim: true,
    minlength: 2,
    maxlength: 4,
    required: 'Plese enter a valid symbol, min 2 characters and max 4'
    },
    // Array of subdocuments
    data: [childSchemaData],
    slug: String

    });

    //we have to PRE-save slug before save the parentSchemaSymbol into DB
    parentSchemaSymbol.pre('save', function (next) {
    if (!this.isModified('symbol')) {
    next()//skip it
    return//stop this function from running
    }
    this.slug = slug(this.symbol)
    next()
    //TODO make more resiliant soslug are unique
    })

    module.exports = mongoose.model('Stock', parentSchemaSymbol)


    Controller - webApiController.js



    const mongoose = require('mongoose')
    const axios = require('axios')

    require('../models/Stock')
    const parentSchemaSymbol = mongoose.model('Stock')



    mongoose.Promise = global.Promise // Tell Mongoose to use ES6 promises
    // Connect to our Database and handle any bad connections
    mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
    mongoose.connection.on('error', (err) => {
    console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`)
    })

    exports.webApi = (req, res) => {
    let curValue = req.params.symbol

    axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${curValue}&outputsize=compact&apikey=TUVR`)
    .then(response => {
    return highLow = Object.keys(response.data['Time Series (Daily)']).map(date => {
    return {
    date: Date.parse(date),
    open: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['1. open']) * 100) / 100,
    high: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['2. high']) * 100) / 100,
    low: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['3. low']) * 100) / 100,
    close: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['4. close']) * 100) / 100,
    volume: parseInt(response.data['Time Series (Daily)'][date]['5. volume'])
    }
    })

    })
    .then(_ => {

    let curValueSchema = new parentSchemaSymbol()

    curValueSchema.symbol = curValue
    highLow.map(item => {
    curValueSchema.data.push(item)
    })
    const query = { symbol: `${curValue.toUpperCase()}` }
    const update = { $addToSet: { data: [curValueSchema.data] } }
    const options = { upsert: true, new: true }
    curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
    console.log('Saved the symbol', doc)
    return res.send(highLow)
    }).catch(e => {
    console.log(e)
    })
    })
    .catch(error => {
    console.log(error)
    })
    }


    Here is the piece of code that I am looking to fix. The rest is working:



     let curValueSchema = new parentSchemaSymbol()

    curValueSchema.symbol = curValue
    highLow.map(item => {
    curValueSchema.data.push(item)
    })
    const query = { symbol: `${curValue.toUpperCase()}` }
    const update = curValueSchema
    const options = { upsert: true, new: true }
    curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
    console.log('Saved the symbol', doc)
    return res.send(highLow)
    }).catch(e => {
    console.log(e)
    })


    Here is the error I am getting



    TypeError: curValueSchema.findOneAndUpdate is not a function
    at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:55:22)
    at process._tickCallback (internal/process/next_tick.js:178:7)


    Here is the data = highLow



    enter image description here



    SOLUTION



    Because Mongoose by default creates a new MongoDB ObjectId ( this hidden _id field) every time you pass it a Javascript Object to update the field of a document.



    To go around you can tell Mongoose to not create a new ObjectId, by making sure your mongoose schema is as followed:



    Folder - Models - Stock.js



    const mongoose = require('mongoose')
    mongoose.Promise = global.Promise
    mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
    const slug = require('slug')


    const childSchemaData = new mongoose.Schema({
    "_id": false,
    date: mongoose.Decimal128,
    open: mongoose.Decimal128,
    high: mongoose.Decimal128,
    low: mongoose.Decimal128,
    close: mongoose.Decimal128,
    volume: mongoose.Decimal128
    })

    const parentSchemaSymbol = new mongoose.Schema({
    "_id": false,
    symbol: {
    type: String,
    trim: true,
    minlength: 2,
    maxlength: 4,
    required: 'Plese enter a valid symbol, min 2 characters and max 4'
    },
    // Array of subdocuments
    data: [childSchemaData],
    slug: String

    });

    //we have to PRE-save slug before save the parentSchemaSymbol into DB
    parentSchemaSymbol.pre('save', function (next) {
    if (!this.isModified('symbol')) {
    next()//skip it
    return//stop this function from running
    }
    this.slug = slug(this.symbol)
    next()
    //TODO make more resiliant soslug are unique
    })

    module.exports = mongoose.model('Stock', parentSchemaSymbol)


    Controller - webApiController.js



    let curValueSchema = new parentSchemaSymbol()

    curValueSchema.symbol = curValue
    highLow.map(item => {
    curValueSchema.data.push(item)
    })
    const query = { symbol: `${curValue.toUpperCase()}` }
    const update = curValueSchema
    const options = { upsert: true, new: true }
    parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc => {
    console.log('Saved the symbol', doc)
    return res.send(highLow)
    }).catch(e => {
    console.log(e)
    })









    share|improve this question



























      0












      0








      0








      I am trying to save and update findOneAndUpdate() ({upsert: true} - creates the object if it doesn't exist) the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save/update it under the Child Schema in the database. How can I do this with nodejs and mongoose? Here is the code that I tried....



      Folder - Models - Stock.js



      const mongoose = require('mongoose')
      mongoose.Promise = global.Promise
      mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
      const slug = require('slug')


      const childSchemaData = new mongoose.Schema({
      date: mongoose.Decimal128,
      open: mongoose.Decimal128,
      high: mongoose.Decimal128,
      low: mongoose.Decimal128,
      close: mongoose.Decimal128,
      volume: mongoose.Decimal128
      })

      const parentSchemaSymbol = new mongoose.Schema({
      symbol: {
      type: String,
      trim: true,
      minlength: 2,
      maxlength: 4,
      required: 'Plese enter a valid symbol, min 2 characters and max 4'
      },
      // Array of subdocuments
      data: [childSchemaData],
      slug: String

      });

      //we have to PRE-save slug before save the parentSchemaSymbol into DB
      parentSchemaSymbol.pre('save', function (next) {
      if (!this.isModified('symbol')) {
      next()//skip it
      return//stop this function from running
      }
      this.slug = slug(this.symbol)
      next()
      //TODO make more resiliant soslug are unique
      })

      module.exports = mongoose.model('Stock', parentSchemaSymbol)


      Controller - webApiController.js



      const mongoose = require('mongoose')
      const axios = require('axios')

      require('../models/Stock')
      const parentSchemaSymbol = mongoose.model('Stock')



      mongoose.Promise = global.Promise // Tell Mongoose to use ES6 promises
      // Connect to our Database and handle any bad connections
      mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
      mongoose.connection.on('error', (err) => {
      console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`)
      })

      exports.webApi = (req, res) => {
      let curValue = req.params.symbol

      axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${curValue}&outputsize=compact&apikey=TUVR`)
      .then(response => {
      return highLow = Object.keys(response.data['Time Series (Daily)']).map(date => {
      return {
      date: Date.parse(date),
      open: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['1. open']) * 100) / 100,
      high: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['2. high']) * 100) / 100,
      low: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['3. low']) * 100) / 100,
      close: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['4. close']) * 100) / 100,
      volume: parseInt(response.data['Time Series (Daily)'][date]['5. volume'])
      }
      })

      })
      .then(_ => {

      let curValueSchema = new parentSchemaSymbol()

      curValueSchema.symbol = curValue
      highLow.map(item => {
      curValueSchema.data.push(item)
      })
      const query = { symbol: `${curValue.toUpperCase()}` }
      const update = { $addToSet: { data: [curValueSchema.data] } }
      const options = { upsert: true, new: true }
      curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
      console.log('Saved the symbol', doc)
      return res.send(highLow)
      }).catch(e => {
      console.log(e)
      })
      })
      .catch(error => {
      console.log(error)
      })
      }


      Here is the piece of code that I am looking to fix. The rest is working:



       let curValueSchema = new parentSchemaSymbol()

      curValueSchema.symbol = curValue
      highLow.map(item => {
      curValueSchema.data.push(item)
      })
      const query = { symbol: `${curValue.toUpperCase()}` }
      const update = curValueSchema
      const options = { upsert: true, new: true }
      curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
      console.log('Saved the symbol', doc)
      return res.send(highLow)
      }).catch(e => {
      console.log(e)
      })


      Here is the error I am getting



      TypeError: curValueSchema.findOneAndUpdate is not a function
      at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:55:22)
      at process._tickCallback (internal/process/next_tick.js:178:7)


      Here is the data = highLow



      enter image description here



      SOLUTION



      Because Mongoose by default creates a new MongoDB ObjectId ( this hidden _id field) every time you pass it a Javascript Object to update the field of a document.



      To go around you can tell Mongoose to not create a new ObjectId, by making sure your mongoose schema is as followed:



      Folder - Models - Stock.js



      const mongoose = require('mongoose')
      mongoose.Promise = global.Promise
      mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
      const slug = require('slug')


      const childSchemaData = new mongoose.Schema({
      "_id": false,
      date: mongoose.Decimal128,
      open: mongoose.Decimal128,
      high: mongoose.Decimal128,
      low: mongoose.Decimal128,
      close: mongoose.Decimal128,
      volume: mongoose.Decimal128
      })

      const parentSchemaSymbol = new mongoose.Schema({
      "_id": false,
      symbol: {
      type: String,
      trim: true,
      minlength: 2,
      maxlength: 4,
      required: 'Plese enter a valid symbol, min 2 characters and max 4'
      },
      // Array of subdocuments
      data: [childSchemaData],
      slug: String

      });

      //we have to PRE-save slug before save the parentSchemaSymbol into DB
      parentSchemaSymbol.pre('save', function (next) {
      if (!this.isModified('symbol')) {
      next()//skip it
      return//stop this function from running
      }
      this.slug = slug(this.symbol)
      next()
      //TODO make more resiliant soslug are unique
      })

      module.exports = mongoose.model('Stock', parentSchemaSymbol)


      Controller - webApiController.js



      let curValueSchema = new parentSchemaSymbol()

      curValueSchema.symbol = curValue
      highLow.map(item => {
      curValueSchema.data.push(item)
      })
      const query = { symbol: `${curValue.toUpperCase()}` }
      const update = curValueSchema
      const options = { upsert: true, new: true }
      parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc => {
      console.log('Saved the symbol', doc)
      return res.send(highLow)
      }).catch(e => {
      console.log(e)
      })









      share|improve this question
















      I am trying to save and update findOneAndUpdate() ({upsert: true} - creates the object if it doesn't exist) the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save/update it under the Child Schema in the database. How can I do this with nodejs and mongoose? Here is the code that I tried....



      Folder - Models - Stock.js



      const mongoose = require('mongoose')
      mongoose.Promise = global.Promise
      mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
      const slug = require('slug')


      const childSchemaData = new mongoose.Schema({
      date: mongoose.Decimal128,
      open: mongoose.Decimal128,
      high: mongoose.Decimal128,
      low: mongoose.Decimal128,
      close: mongoose.Decimal128,
      volume: mongoose.Decimal128
      })

      const parentSchemaSymbol = new mongoose.Schema({
      symbol: {
      type: String,
      trim: true,
      minlength: 2,
      maxlength: 4,
      required: 'Plese enter a valid symbol, min 2 characters and max 4'
      },
      // Array of subdocuments
      data: [childSchemaData],
      slug: String

      });

      //we have to PRE-save slug before save the parentSchemaSymbol into DB
      parentSchemaSymbol.pre('save', function (next) {
      if (!this.isModified('symbol')) {
      next()//skip it
      return//stop this function from running
      }
      this.slug = slug(this.symbol)
      next()
      //TODO make more resiliant soslug are unique
      })

      module.exports = mongoose.model('Stock', parentSchemaSymbol)


      Controller - webApiController.js



      const mongoose = require('mongoose')
      const axios = require('axios')

      require('../models/Stock')
      const parentSchemaSymbol = mongoose.model('Stock')



      mongoose.Promise = global.Promise // Tell Mongoose to use ES6 promises
      // Connect to our Database and handle any bad connections
      mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
      mongoose.connection.on('error', (err) => {
      console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`)
      })

      exports.webApi = (req, res) => {
      let curValue = req.params.symbol

      axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${curValue}&outputsize=compact&apikey=TUVR`)
      .then(response => {
      return highLow = Object.keys(response.data['Time Series (Daily)']).map(date => {
      return {
      date: Date.parse(date),
      open: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['1. open']) * 100) / 100,
      high: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['2. high']) * 100) / 100,
      low: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['3. low']) * 100) / 100,
      close: Math.round(parseFloat(response.data['Time Series (Daily)'][date]['4. close']) * 100) / 100,
      volume: parseInt(response.data['Time Series (Daily)'][date]['5. volume'])
      }
      })

      })
      .then(_ => {

      let curValueSchema = new parentSchemaSymbol()

      curValueSchema.symbol = curValue
      highLow.map(item => {
      curValueSchema.data.push(item)
      })
      const query = { symbol: `${curValue.toUpperCase()}` }
      const update = { $addToSet: { data: [curValueSchema.data] } }
      const options = { upsert: true, new: true }
      curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
      console.log('Saved the symbol', doc)
      return res.send(highLow)
      }).catch(e => {
      console.log(e)
      })
      })
      .catch(error => {
      console.log(error)
      })
      }


      Here is the piece of code that I am looking to fix. The rest is working:



       let curValueSchema = new parentSchemaSymbol()

      curValueSchema.symbol = curValue
      highLow.map(item => {
      curValueSchema.data.push(item)
      })
      const query = { symbol: `${curValue.toUpperCase()}` }
      const update = curValueSchema
      const options = { upsert: true, new: true }
      curValueSchema.findOneAndUpdate(query, update, options).then(doc => {
      console.log('Saved the symbol', doc)
      return res.send(highLow)
      }).catch(e => {
      console.log(e)
      })


      Here is the error I am getting



      TypeError: curValueSchema.findOneAndUpdate is not a function
      at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:55:22)
      at process._tickCallback (internal/process/next_tick.js:178:7)


      Here is the data = highLow



      enter image description here



      SOLUTION



      Because Mongoose by default creates a new MongoDB ObjectId ( this hidden _id field) every time you pass it a Javascript Object to update the field of a document.



      To go around you can tell Mongoose to not create a new ObjectId, by making sure your mongoose schema is as followed:



      Folder - Models - Stock.js



      const mongoose = require('mongoose')
      mongoose.Promise = global.Promise
      mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
      const slug = require('slug')


      const childSchemaData = new mongoose.Schema({
      "_id": false,
      date: mongoose.Decimal128,
      open: mongoose.Decimal128,
      high: mongoose.Decimal128,
      low: mongoose.Decimal128,
      close: mongoose.Decimal128,
      volume: mongoose.Decimal128
      })

      const parentSchemaSymbol = new mongoose.Schema({
      "_id": false,
      symbol: {
      type: String,
      trim: true,
      minlength: 2,
      maxlength: 4,
      required: 'Plese enter a valid symbol, min 2 characters and max 4'
      },
      // Array of subdocuments
      data: [childSchemaData],
      slug: String

      });

      //we have to PRE-save slug before save the parentSchemaSymbol into DB
      parentSchemaSymbol.pre('save', function (next) {
      if (!this.isModified('symbol')) {
      next()//skip it
      return//stop this function from running
      }
      this.slug = slug(this.symbol)
      next()
      //TODO make more resiliant soslug are unique
      })

      module.exports = mongoose.model('Stock', parentSchemaSymbol)


      Controller - webApiController.js



      let curValueSchema = new parentSchemaSymbol()

      curValueSchema.symbol = curValue
      highLow.map(item => {
      curValueSchema.data.push(item)
      })
      const query = { symbol: `${curValue.toUpperCase()}` }
      const update = curValueSchema
      const options = { upsert: true, new: true }
      parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc => {
      console.log('Saved the symbol', doc)
      return res.send(highLow)
      }).catch(e => {
      console.log(e)
      })






      javascript node.js mongodb mongoose






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 5:22







      John John

















      asked Nov 16 '18 at 1:44









      John John John John

      778




      778
























          3 Answers
          3






          active

          oldest

          votes


















          1















          1. findOneAndUpdate and update is a model method and its available for instance of the model, So you're getting method not found error.





          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })








          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:36













          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58



















          1














          Instead of:



          curValueSchema.findOneAndUpdate


          Do:



          parentSchemaSymbol.findOneAndUpdate





          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:39











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58



















          1














          It's a model's method, not a instance.
          Replace instance name with scheme name.






          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:40











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53330294%2fmongodb-mongoose-query-findoneandupdate-doesnt-update-duplicates-the-db%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1















          1. findOneAndUpdate and update is a model method and its available for instance of the model, So you're getting method not found error.





          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })








          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:36













          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58
















          1















          1. findOneAndUpdate and update is a model method and its available for instance of the model, So you're getting method not found error.





          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })








          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:36













          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58














          1












          1








          1








          1. findOneAndUpdate and update is a model method and its available for instance of the model, So you're getting method not found error.





          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })








          share|improve this answer














          1. findOneAndUpdate and update is a model method and its available for instance of the model, So you're getting method not found error.





          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })








          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })





          let curValueSchema = new parentSchemaSymbol()
          curValueSchema.symbol = curValue
          highLow.map(item = > {
          curValueSchema.data.push(item)
          })
          const query = {
          symbol: `$ {
          curValue.toUpperCase()
          }`
          }
          const update = curValueSchema
          const options = {
          upsert: true,
          new: true
          }
          parentSchemaSymbol.findOneAndUpdate(query, update, options).then(doc = > {
          console.log('Saved the symbol', doc)
          return res.send(highLow)
          }).
          catch (e = > {
          console.log(e)
          })






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 3:16









          Raja SekarRaja Sekar

          1,550722




          1,550722













          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:36













          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58



















          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:36













          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58

















          Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

          – John John
          Nov 16 '18 at 3:36







          Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: `${curValue.toUpperCase()}` } does not apply toUpperCase()

          – John John
          Nov 16 '18 at 3:36















          to avoid the duplication I need to add "_id": false to the child and parent Schema

          – John John
          Nov 16 '18 at 4:58





          to avoid the duplication I need to add "_id": false to the child and parent Schema

          – John John
          Nov 16 '18 at 4:58













          1














          Instead of:



          curValueSchema.findOneAndUpdate


          Do:



          parentSchemaSymbol.findOneAndUpdate





          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:39











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58
















          1














          Instead of:



          curValueSchema.findOneAndUpdate


          Do:



          parentSchemaSymbol.findOneAndUpdate





          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:39











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58














          1












          1








          1







          Instead of:



          curValueSchema.findOneAndUpdate


          Do:



          parentSchemaSymbol.findOneAndUpdate





          share|improve this answer













          Instead of:



          curValueSchema.findOneAndUpdate


          Do:



          parentSchemaSymbol.findOneAndUpdate






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 2:59









          hoangdvhoangdv

          1,9281614




          1,9281614













          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:39











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58



















          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:39











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58

















          Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

          – John John
          Nov 16 '18 at 3:39





          Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

          – John John
          Nov 16 '18 at 3:39













          to avoid the duplication I need to add "_id": false to the child and parent Schema

          – John John
          Nov 16 '18 at 4:58





          to avoid the duplication I need to add "_id": false to the child and parent Schema

          – John John
          Nov 16 '18 at 4:58











          1














          It's a model's method, not a instance.
          Replace instance name with scheme name.






          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:40











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58
















          1














          It's a model's method, not a instance.
          Replace instance name with scheme name.






          share|improve this answer
























          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:40











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58














          1












          1








          1







          It's a model's method, not a instance.
          Replace instance name with scheme name.






          share|improve this answer













          It's a model's method, not a instance.
          Replace instance name with scheme name.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 3:10









          whyourwhyour

          113




          113













          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:40











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58



















          • Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

            – John John
            Nov 16 '18 at 3:40











          • to avoid the duplication I need to add "_id": false to the child and parent Schema

            – John John
            Nov 16 '18 at 4:58

















          Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

          – John John
          Nov 16 '18 at 3:40





          Aha , it makes sence. But for same reason it does not work as expected. It is inserting dumplicate values and pre('save') is not working. Also const query = { symbol: ${curValue.toUpperCase()} } does not apply toUpperCase()

          – John John
          Nov 16 '18 at 3:40













          to avoid the duplication I need to add "_id": false to the child and parent Schema

          – John John
          Nov 16 '18 at 4:58





          to avoid the duplication I need to add "_id": false to the child and parent Schema

          – John John
          Nov 16 '18 at 4:58


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53330294%2fmongodb-mongoose-query-findoneandupdate-doesnt-update-duplicates-the-db%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Lugert, Oklahoma