0

I'm building a MEAN stack web application.

I have a model in mongoose like this. A model name analyses, where inside , there is a property call points which is another small model name analysis

//model file
var mongoose = require('mongoose');
var Schema = mongoose.Schema; 

var analysis = new Schema({ 
  ref_id: String,
  ele_name: String,
  pos_x: Number,
  pos_y: Number,
  pos_pix_x: Number,
  pos_pix_y: Number,
});

var analyses = new Schema({    
  img_id: String,
  store_file_name:String,
  points: {
    type: [analysis],
    default: undefined
  },    
});

module.exports = mongoose.model('analyses', analyses);

In the database , after I create an entry. there something like this enter image description here

As you can see, there an id of analyses (5bb...820e) inside have an array of points ( analysis), each has their own id ( 5bb...26d)

Now if I want to update this. I use ExpressJS to define the update API of the server

// API define file
var express = require('express');
var analysesRoutes = express.Router();

// Require Item model in our routes module
var Analyses = require('../models/analyses');

//  Defined update route
analysesRoutes.route('/update/:id').put(function (req, res) {
  Analyses.findById(req.params.id, function(err, analyses) {
    if (!analyses)
      return next(new Error('Could not load Document'));
    else {
      for ( item of Object.keys(req.body)){
        analyses[item] = req.body[item];
      }
      analyses.save().then(analyses => {
        res.json({...analyses, status: 200});
      })
        .catch(err => {
          res.status(400).send("unable to update the database");
        });
    }
  });
});

But my problem here is if I want to update only 1 analysis point, I have to send the request to update the big analyses object ( call out id 5bb...820e). Something like this :

//service file
  updateAnalyses(newObj, id) {
    const uri = 'http://localhost:4000/analyses/update/' + id;

    this
      .http
      .put(uri, newObj)
      .subscribe(res => console.log('Done'));
  }
 // Where newObj here is a big analyses object contains all the unnecessary detail + the point need to be updated

In fact, that point also have an id ( 5bb..26d) itself, is there anyway to update directly to that analysis point ??

Jake Lam
  • 3,254
  • 3
  • 25
  • 44

1 Answers1

0

Similar question was answered before in Stack overflow. You can refer to it from here: MongoDB update data in nested field

P.S. There are many answers related to mongodb. Personally the parent.$.child notation worked for me.