代码之家  ›  专栏  ›  技术社区  ›  Non Plus Ultra

在子文档中推送JSON文档只插入ObjectId

  •  1
  • Non Plus Ultra  · 技术社区  · 7 年前

    我在Mongoose中创建了一个模型:

    var userWalletSchema = new Schema({
       userid: {type: Schema.ObjectId, ref: 'users'},
       Transactions: [{
             Datum: {Type: Date},
             CODE: {Type: String},
             aantal: {Type: Number},
             soortTransactie: {Type: String}, 
             bedrag: {Type:Number}
       }]
    },
    {collection:'userWallet'});
    

    我插入以下文件:

    var newRecord = { Datum: '2017-12-21T00:00:00+01:00',
    CODE: 'IE00B3VWN518',
    aantal: 48,
    soortTransactie: 'Aankoop',
    bedrag: 478 };
    

    使用此代码:

    UserWallet.findOneAndUpdate(
       { userid: mongoose.Types.ObjectId(req.user.id)},
       { $push: {Transactions: newRecord}},
       { upsert: false },
       function (err, model) {
          console.log(err);
          console.log(model);
       });
    

    我尝试了几种排列和选项,但都给出了相同的结果:记录被推送到事务数组,但它始终包含值\u id:ObjectId('5a490c3376dfb6630464f6e1')(当然id会更改),但从未包含我要插入的文档。

    这里出了什么问题?我希望插入一个新的子文档会很容易。

    解决方案:我发现了问题。我用大写T键入了“Type”,这个词在JavaScript中应该都是小写的。真傻,我花了两天时间才发现。

    2 回复  |  直到 7 年前
        1
  •  1
  •   David Vicente    7 年前

    你可以尝试另一种方法。首先找到对象,将新事务添加到对象中,然后保存它。

    UserWallet.findOneAndUpdate({ userid: mongoose.Types.ObjectId(req.user.id)}, function(err, userWallet) {
        userWallet.Transactions.push(newRecord);
        userWallet.save();
    });
    
        2
  •  1
  •   Ahamad I Milazi    7 年前

    你在储蓄方面的做法是可以的。如果检查模式,则保存的是ObjectId,而不一定是实际的对象。

    如果要保存User类型的对象,则可以将实际用户模型放入UserWallet方案声明中。

    然而,对于您的情况,我建议的方法是保持现状并使用 人口 检索用户钱包时。

    例子:

    UserWallet.find().populate('user_id').exec(function(err,userWallets){
    
    });
    

    现在,UserWallet的user\u id字段将具有ObjectId引用的实际用户对象。您可以在 documentation