简体   繁体   中英

How to insert data into MongoDB collection?

I'm using NodeJS with Mongoose. I've two tables into db.js:

const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema(
    {
        username: { type: String, required: true, unique: true },
        email:    { type: String, required: true, unique: true },
        password: { type: String, required: true }
    },
    { collection: 'users' }
    
)



const model = mongoose.model('UserSchema', UserSchema)

const AccountSchema = new mongoose.Schema(
    {
        username: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'hahaha' },
        balance:  { type: Number, required: true }
    },
    { collection: 'accounts' }
    
)


module.exports.UserSchema = model
module.exports.AccountSchema = model

As you can see the first collection contains users ( username , email , password ). The second collection represents a bank account, related to a specific user . So, it has two fields: user (foreign key) and balance ($100, ie). First question: is my code correct to accomplish this task? Second question: how can I insert data into the AccountSchema ? I obviously want to insert data only if the user exists into Userschema . I think that this doesn't work:

const Schema = require('./model/db')
app.post('/api/addaccount', async (req, res) => {
    const { username, balance } = req.body

    try {
        const response = await Schema.AccountSchema.create({
            username,
            balance
        })
        console.log('User account successfully: ', response)
        res.json({status : "ok"})

    } catch (error) {

        throw error
    }   
})

How can I do this?

This won't work. You've to query the User model first to check if any user exists with this username. If yes, you'll continue to store data in the Account model, if not you'll return a response something like user doesn't exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM