Scott Selke
Scott Selke

Reputation: 107

Mongoose + Mongodb User.update not working

What I am trying to do is create a new collection, and push that collection into a specific User.collections array. I have read many stackoverflow posts and they all say to use either User.update() or User.findOneAndUpdate(). I am have no luck with either. I can create a Collection and that is saved to mongo so I know I am indeed accessing the db. Here is my code, if any of you can help I would appreciate it.

User Schema

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({

    googleID: String,
    givenName: String,
    familyName: String,
    collections: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "collection"
        }
    ]
});

mongoose.model('users', userSchema);

Collection Schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const collectionSchema = new Schema({
    type: String,
    name: String,
    gamesCollected: [
        {
            id: Number
        }
    ]
});

mongoose.model('collection', collectionSchema);

And my route:

router.get('/get_collection', (req, res) => {    
    const collection = new Collection({
        type: 'SNES',
        name: 'First SNES Collection',
        gamesCollected: [{ id: 5353 }]
    }).save();

    User.update({googleID: req.user.googleID}, {$push: {collections: collection}});
});

Upvotes: 0

Views: 44

Answers (1)

Akrion
Akrion

Reputation: 18515

Save is not a synchronous operation but asynchronous so you need to use the promise it returns and handle it and once it is complete then update the user model. Something among these lines:

router.get('/get_collection', async (req, res) => {
    let collection = new Collection({
        type: 'SNES',
        name: 'First SNES Collection',
        gamesCollected: [{ id: 5353 }]
    })
    await collection.save().exec();
    await User.update(
     {googleID: req.user.googleID}, 
     {$push: {collections: collection._id}}
    ).exec();
});

Upvotes: 3

Related Questions