【问题标题】:How to update a nested model in mongoose and mongodb如何在 mongoose 和 mongodb 中更新嵌套模型
【发布时间】:2019-03-15 17:41:15
【问题描述】:

我正在构建一个 MEAN 堆栈 Web 应用程序。

我在mongoose 有一个这样的模型。模型名称analyses,其中内部有一个属性调用points,这是另一个小的模型名称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);

在数据库中,我创建了一个条目之后。有这样的东西

如您所见,analyses (5bb...820e) 的 id 内部有一个点数组(analysis),每个点都有自己的 id ( 5bb...26d)

现在如果我想更新这个。我使用ExpressJS来定义服务器的更新API

// 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");
        });
    }
  });
});

但我的问题是如果我只想更新 1 个analysis 点,我必须发送更新大analyses 对象的请求(调用id 5bb...820e)。像这样的:

//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

其实那个点本身也有一个id (5bb..26d),有没有办法直接更新到那个分析点??

【问题讨论】:

    标签: mongodb express mongoose model mean-stack


    【解决方案1】:

    之前在堆栈溢出中回答了类似的问题。 您可以从这里参考:MongoDB update data in nested field

    附:有很多与mongodb相关的答案。就我个人而言,parent.$.child 符号对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2023-01-18
      • 2021-03-26
      • 1970-01-01
      • 2017-07-06
      • 2020-10-09
      • 2013-11-06
      相关资源
      最近更新 更多