S
S
squadbrodyaga2020-11-03 18:08:48
MongoDB
squadbrodyaga, 2020-11-03 18:08:48

How to add data to MongoDB array?

Hello, tell me how to add data to MongoDB array.
To be more specific, if the user followed the referral link, then it must be
added to the array ( referrals = []) of the person who invited this referral.

This is what the user schema looks like:

userSchema
const userSchema = new Schema({
    login: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    referrals: []
})

// Так я ищу человека, по ссылке которого перешли
const referrer = await User.findOne({ _id: req.query.ref })

// Так я сохраняю нового пользователя в базу данных
const user = new User({ 
    login: ...,
    email: ...,
    password: ...
})
await user.save()

// А это я пытался добавить нового реферала в массив, пользователь которого его пригласил.
referrer.update({
    referrals: user
})
// Но моя татарская логика меня подвела и такой код не сработал

Can you suggest what needs to be done? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2020-11-03
@squadbrodyaga

Something like this:

const userSchema = new Schema({
    login: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    referrals: [{
      type: Schema.Types.ObjectId,
      ref: 'User',
    }]
})

referrer.update({
    $push: {
        referrals: user._id
    }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question