Как обновить существующий документ MongoDB с помощью Nested JSON, используя Angular? - PullRequest
0 голосов
/ 06 января 2020

Я пытаюсь сохранить массив JSON в существующем документе с id , который вошел в систему. У меня нет идеи, как отправить этот массив в бэкэнд.

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

1 Ответ

0 голосов
/ 06 января 2020

Вот базовый c код, пожалуйста, обновите его соответственно:

/** 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();
  }
});
...