Saturday, 1 April 2017

Nodejs + Mongoose custom validator to check if unique, if so, update existing record

I'm connecting to an API and copying some of the result data into my own database to be manipulated afterward. Basically I query the API and search for "restaurants", and it brings me a list of restaurants, which I copy some relevant info, such as the unique ID of the restaurant. Let's say in this case one of the restaurants was "Bubba's Bar & Grill". So I insert this and many other restaurants into my own MongoDB database.

Then I connect to the same API and run a search for "bars" and somewhere in this list it will have "Bubba's Bar & Grill" again. Since I want to keep unique records in my own database, what I'd like to do is have a field as type Array that will contain the types of places a single record will be. So in this case the object in MongoDB will look something like this:

{
  name: 'Bubba\'s Bar & Grill',
  id: 'bubbas-bar-and-grill',
  type: ['bar', 'restaurant']
}

I believe the best way to do this is to have some type of custom mongoose validator, or a .pre('save') function to make this happen. I'd tried several ways but unfortunately the MEAN stack is not my primary proficiency as a software developer. Anyone have any ideas for the best way to approach this issue?

Here's my code so far:

server.js

var mongoose    = require('mongoose'),
    api         = require('myapi')

// API Credentials
var id     = 'myapi-id'
var secret = 'myapi-secret'

// Connect to MongoDB
mongoose.Promise = global.Promise
mongoose.connect('mongodb://127.0.0.1/db')
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err))

// Import Models
var Location = require('./model.places.js')

//Get API Token
api.call('API', 'getAccessToken', {
  'appId': id,
  'appSecret': secret
}).on('success', (token) => {
  var access_token = token.access_token
  console.log('Access token: '+ access_token)
  // Populate Database with Places
  api.call('API', 'getBusinesses', {
    'accessToken': access_token,
    'term': 'restaurant'
  }).on('success', (payload) => {
    for (var i = 0; i < payload.businesses.length; i++) {
      var location = new Location({
        name: payload.businesses[i].name,
        id: payload.businesses[i].id
        type: 'restaurant'
      })
      location.save(function (err) {
        if (err) { console.log(err) }
      })
    }
  })
})

model.places.js

var mongoose = require('mongoose')

var Place = new mongoose.Schema({
  name: { type: String, required: true, trim: true },
  id: { type: String, required: true, trim: true, unique: true }
  type: { type: Array, default: [] }
})

module.exports = mongoose.model('places', PlaceSchema)



via robotsushi

No comments:

Post a Comment