//index.js const express = require('express'); const ejs=require('ejs'); const mongoose = require('mongoose'); const Schema = mongoose.Schema; 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){ console.log('coinName', coinName) console.log('order', order._doc) const coin = await Coin.findOneAndUpdate( {name:coinName}, {$push: { order: order._doc }} ); }
models/coins.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const coinSchema = new mongoose.Schema( { name: String, description: String, order: Schema.Types.Mixed } ); const Coin = mongoose.model('Coin',coinSchema); module.exports = Coin
models/orders.js
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
Once the index.js is executed, you can see the data created in mongodb database, which is also created if not there already.
No comments:
Post a Comment