首页 > 解决方案 > Mongoose + Mongodb User.update 不工作

问题描述

我要做的是创建一个新集合,并将该集合推送到特定的 User.collections 数组中。我已经阅读了许多 stackoverflow 帖子,他们都说要使用 User.update() 或 User.findOneAndUpdate()。我也没有运气。我可以创建一个集合并将其保存到 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}});
});

标签: javascriptmongodbexpressmongoosemongoose-schema

解决方案


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

推荐阅读