【问题标题】:Mongoose + Mongodb User.update not workingMongoose + Mongodb User.update 不工作
【发布时间】:2019-04-09 04:03:16
【问题描述】:

我要做的是创建一个新集合,然后将该集合推送到特定的 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}});
});

【问题讨论】:

    标签: javascript mongodb express mongoose mongoose-schema


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      相关资源
      最近更新 更多