Reputation: 357
I have a user schema like this
const userSchema = new Schema({
username: {
type: String,
unique: true,
required: true,
},
cardIds: [{
type: Schema.Types.ObjectId,
ref: 'cards',
}],
})
mongoose.model('users', userSchema)
I'm attempting to do two things in the pre save hook for user: first, saving each card with the user id and second, adding the cardIds
to the User. My code:
const Card = mongoose.model('cards')
userSchema.pre('save', function (next) {
if (this.cardIds.length === 0) {
cardList.forEach(async card => {
const newCard = await new Card({ ...card, user: this })
this.cardIds.push(newCard) // this is not working
newCard.save() // this is working
})
}
next()
})
This will add each card into the cards
collection with the correct user._id
, however, each user will still have an empty array for cardIds
.
The way I save the user is (omitting error handling/validation for convenience):
app.post('/users/new', async (req, res) => {
const newUser = await new User({ username: req.body.username })
await newUser.save()
return res.json({ message: 'User created successfully' })
})
Upvotes: 2
Views: 932
Reputation: 46441
This is basically a javascript code this.cardIds.push(newCard)
to push an element to an array but It doesn't do anything to your mongo database...
Therefore, In order to update an array in mongodb you need to use $push operator
userSchema.pre('save', function (next) {
if (this.cardIds.length === 0) {
cardList.forEach(async card => {
const newCard = new Card({ ...card, user: this })
const saveNewCard = await newCard.save() // this is working
const updateUser = await User.update(
{ _id: this._id },
{ $push: { cardIds: saveNewCard._id }}
)
})
}
next()
})
Upvotes: 2