Node.js 无法将对象添加到MongoDB的另一个对象的数组中,如何修复该问题?

Node.js 无法将对象添加到MongoDB的另一个对象的数组中,如何修复该问题?,node.js,mongoose,Node.js,Mongoose,我的模型: coins.js const mongoose = require('mongoose'); const {orderSchema} = require('./orders'); const coinSchema = new mongoose.Schema( { name: String, description: String, orders: [orderSchema], } ); const C

我的模型:

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
命令

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();
}
我得到的错误

(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.
我正在尝试创建两个文档。其中coin文档包含订单的任何数组。 订单是另一种文件。因此,我编写了addOrder函数,将其添加到硬币中,并在其创建结束时提供名称

但是在运行时出现上述错误,并且这两个文档在mongodb中没有链接,但它们正在创建


请建议如何设置此关系。

首先,您需要更改并添加Coin文档中名为“orders”的字段

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);
}
然后,请尝试更改addOrder函数,如下所示

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

这是您可以获得的源代码链接

find()。您可以循环
coin
并在循环内更新,或者如果您试图只选择一个文档,则使用
findOne()
方法。获取此错误。我需要对硬币的型号做些什么改变吗?未经处理的PromisejectionWarning:ValidationError:Coin验证失败:orders:Cast to embedded值“[Function:Mixed]{\n'+”schemaName:'Mixed',\n'+'默认选项:{}、\n'+'get:[函数(匿名)],\n'+'集:[函数:集]\n'+'}”(类型字符串)路径“orders”这是您可以下载的源代码链接。非常感谢,它正在工作。当检索到与之相关的硬币时,有没有关于如何获取所有订单聚合值的建议。没问题,但您能详细解释一下这个问题吗?你能接受我的答案是正确的吗?谢谢。我收集硬币,每一枚硬币作为子文档链接到多个订单。所以,当一枚硬币被取回时,它应该得到价格场和硬币场的平均值。