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

问题描述 投票:1回答:2

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

我已经尝试了几种排列和选项,但都给出了相同的结果:一条记录​​被推送到Transactions数组,但它总是包含值_id:ObjectId('5a490c3376dfb6630464f6e1')(当然Id更改),但从来没有文档我打算插入。

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

解决方案:我发现了问题。我用大写字母T键入“Type”,JavaScript中的单词应全部小写。太傻了,花了我2​​天才发现它。

json node.js mongodb mongoose push
2个回答
1
投票

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

UserWallet.findOneAndUpdate({ userid: mongoose.Types.ObjectId(req.user.id)}, function(err, userWallet) {
    userWallet.Transactions.push(newRecord);
    userWallet.save();
});

1
投票

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

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

但是,我建议您采用的方法是保持原样,并在检索userWallets时使用填充。

例:

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

});

现在,UserWallet的user_id字段将具有使用ObjectId引用的实际用户对象。您可以在documentation阅读更多有关人口的信息

© www.soinside.com 2019 - 2024. All rights reserved.