Answer the question
In order to leave comments, you need to log in
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:
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
})
// Но моя татарская логика меня подвела и такой код не сработал
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question