猫鼬+ Mongodb User.update不起作用

时间:2018-11-05 18:52:51

标签: javascript mongodb express mongoose mongoose-schema

我想做的是创建一个新集合,并将该集合推入特定的User.collections数组中。我读过许多stackoverflow帖子,他们都说使用User.update()或User.findOneAndUpdate()。我也没有运气。我可以创建一个Collection并将其保存到mongo,所以我知道我确实在访问数据库。这是我的代码,如果有谁可以帮忙,我将不胜感激。

用户架构

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);

集合模式:

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

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

mongoose.model('collection', collectionSchema);

我的路线:

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}});
});

1 个答案:

答案 0 :(得分:2)

Save不是同步操作,而是异步操作,因此您需要使用promise返回并处理它,一旦完成,就更新用户模型。这些行中的一些内容:

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();
});