I am trying to save and update (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. For some reason it adds duplicate values. Is there a way to fix avoid duplicate values? Here is the code that I tried....
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)
})
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
"_id": false - Has to be added to the Schema
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)