Unable to add an object to array in another object of MongoDB, how to fix that?

Viewed 89

My models:

coins.js

const mongoose = require('mongoose');
const {orderSchema} = require('./orders');
const coinSchema = new mongoose.Schema(
    {
        name: String,
        description: String,
        orders: [orderSchema],
        
    }
);

const Coin = mongoose.model('Coin',coinSchema);
module.exports = Coin

orders

const mongoose = require('mongoose');
const orderSchema = new mongoose.Schema(
    {
        description: String,
        purchasePrice: Number,
        purchaseCount: Number,
        purchaseAmount: Number,
        comission:Number
        
    }
);

const Order = mongoose.model('Order',orderSchema);
module.exports.Order = Order
module.exports.orderSchema = orderSchema

index.js

const express = require('express');
const ejs=require('ejs');
const mongoose = require('mongoose');
const Coin = require('./models/coins');

mongoose.connect('mongodb://localhost/playground')
.then(()=>console.log('connected'))
.catch(err => console.error('some error',err))

async function createCoin(){
const Coin = require('./models/coins');
const coin = new Coin(
    {
    name: 'BTT',
    description: 'Bittorrent coin',
    }
);

const result = await coin.save();
console.log(result);
}

createCoin()

async function createOrder(){
    const {Order} = require('./models/orders');
    const order = new Order(
        {
            purchasePrice: 0.54,
            purchaseCount: 200,
            purchaseAmount: 54000,
            comission:23
    
        }
    );
    
    const result = await order.save();
    addOrder('BTT',result)
    console.log(result);
    }
    
createOrder()

async function addOrder(coinName,order){
    const coin = await Coin.find({name:coinName});
    console.log("Writing to Coin:",coin.orders)
    console.log("Writing order:",order)
    coin.orders.push(order);
    coin.save();
}

The error I am getting

(node:5988) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined
    at addOrder (D:\CoinsPortal\index.js:48:17)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:5988) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5988) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I am trying to create two documents. Where coin document contains any array for orders. And order is another document. So, I wrote addOrder function to add it to a coin with the name provided at the end of its creation.

But getting the above error while running it and both the documents are not getting linked in the mongodb, but they are creating.

Please suggest how to setup this relation.

1 Answers

First, you need to change add the field named "orders" in Coin document.

const Schema = mongoose.Schema;

async function createCoin(){
    const Coin = require('./models/coins');
    const coin = new Coin(
        {
        name: 'BTT',
        description: 'Bittorrent coin',
        order: Schema.Types.Mixed,
        }
    );

    const result = await coin.save();
    console.log(result);
}

And then, please try to change the addOrder function as following.

async function addOrder(coinName,order){
    console.log('coinName', coinName)
    console.log('order', order._doc)
    const coin = await Coin.findOneAndUpdate(
        {name:coinName},
        {$push: {
            order: order._doc
            }}
        );
}

Here is the source code link that you can get. link

Related