【问题标题】:How to update existing MongoDB document with Nested JSON using Angular?如何使用 Angular 使用嵌套 JSON 更新现有 MongoDB 文档?
【发布时间】:2020-04-23 15:56:55
【问题描述】:

我正在尝试使用登录的 id 将 JSON 数组存储到现有文档。我不知道如何将此数组发布到后端。

cake.component.ts

export class CakeComponent implements OnInit {
    form: FormGroup;

    constructor(
        public fb: FormBuilder,
        private api: ApiService
    ) { }

    ngOnInit() {
        this.submitForm();
    }

    submitForm() {
        this.form = this.fb.group({
            url: ['', [Validators.required]],
            width : ['', [Validators.required]],
            height: ['', [Validators.required]]
        })
    }

    submitForm() {
        if (this.form.valid) {
            this.api.AddCake(this.form.value).subscribe();
        }
    }
}

现有的 MongoDB 文档 蛋糕

{
    "id": "0001",
    "type": "donut",
    "name": "Cake"
}

预期输出

{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "image": {
        "url": "images/0001.jpg",
        "width": 200,
        "height": 200
    }
}

【问题讨论】:

    标签: node.js angular mongodb mean-stack


    【解决方案1】:

    这是基本代码,请相应更新:

    /** You can split this code into multiple files, schema into a file &
        mongoDB connectivity into a common file & actual DB update can be placed where ever you want */
    
    const mongoose = require('mongoose')
    const Schema = mongoose.Schema;
    
    const cakeSchema = new Schema({
        id: String,
        type: String,
        name: String,
        image: {
            url: String,
            width: Number,
            height: Number
        }
    });
    
    const cakeModel = mongoose.model('Cakes', cakeSchema, 'Cakes');
    
    let form = {
        "url": "images/0001.jpg",
        "width": 200,
        "height": 200
    }
    
    async function myDbConnection() {
    
        const url = 'yourDBConnectionString';
    
        try {
            await mongoose.connect(url, { useNewUrlParser: true });
            console.log('Connected Successfully')
            let db = mongoose.connection;
    
            // You can use .update() or .updateOne() or .findOneAndUpdate()
            let resp = await cakeModel.findOneAndUpdate({ id: '0001' }, { image: form }, { new: true });
            console.log('successfully updated ::', resp)
            db.close();
        } catch (error) {
            console.log('Error in DB Op ::', error);
            db.close();
        }
    }
    
    module.exports = myDbConnection();
    

    更新:

    如果您使用的是mongoDB driver 而不是mongoose

    const MongoClient = require('mongodb').MongoClient;
    
    // Connection URL
    const url = 'yourDBConnectionString';
    
    // Database Name
    const dbName = 'test';
    
    // Create a new MongoClient
    const client = new MongoClient(url);
    
    let form = {
      "url": "images/0001.jpg",
      "width": 200,
      "height": 200
    }
    
    // Use connect method to connect to the Server
    client.connect(async function (err) {
    
      if (err) console.log('DB connection error ::', err)
      console.log("Connected successfully to server");
    
      try {
        // You can use .update() or .updateOne() or .findOneAndUpdate()
        let resp = await client.db(dbName).collection('Cakes').findOneAndUpdate({ id: '0001' }, { $set: { image: form } }, { returnOriginal: false });
        console.log('successfully updated ::', resp , 'resp value ::', resp.value)
        client.close();
      } catch (error) {
        console.log('Error in DB Op ::', error);
        client.close();
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2021-11-30
      • 2015-08-27
      • 1970-01-01
      • 2016-11-23
      • 2011-04-19
      • 2016-08-04
      • 2018-04-23
      相关资源
      最近更新 更多