使用以下代码行我可以更新给定的Transaction(文档),但是当我尝试更新其子文档的属性时,给定的值不会保留。
Transaction.findById('55cf89abe148323e5368dcd5').populate('cryptocurrencies')
.then(function(transaction){
transaction.status = 'completed'; // this updates the transaction status correctly
transaction['cryptocurrencies'][0].status = 'ordered'; // this update is not persisted
return transaction.save()
.then(function(transaction){
console.log(transaction['cryptocurrencies'][0].status); // this shows the status as updated, but it's not persisted
})
})
我更新属性后无法使用行transaction['cryptocurrencies'][0].markModified('status');
。在文档中找不到任何内容:我缺少什么?
更新:我对此进行了进一步测试,发现我必须在文档及其子文档中使用.save()方法。有没有我可以运行一个方法来保存文档及其子文档属性已更改,或者我是否必须运行两个操作来每次保存一个文档?
更新
这是我的型号代码:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TransactionSchema = new Schema({
userId: { type: String, required: true },
status: { type: String, enum: ['unpaid', 'failed', 'paid', 'ordered', 'received', 'withdrawn', 'completed'] },
invoice: String,
saltStatus: String,
saltTransactionId : Number,
saltBank: String,
saltConfirmation: String,
saltAmount : Number,
saltDate : String,
saltResponseCode: String,
cryptocurrencies: [{ type: mongoose.Schema.Types.ObjectId, ref: 'CryptoCurrency' }]
});
var CryptoCurrencySchema = new Schema({
currencyName: String,
price: Number,
amount: Number,
total : Number,
walletAddress: String,
dollarsPaid : Number,
exchangeTransactionId: Number,
coinTransactionId : String,
status: { type: String, enum: ['ordered', 'received', 'withdrawn'] }
});
module.exports.Transaction = mongoose.model('Transaction', TransactionSchema);
module.exports.CryptoCurrency = mongoose.model('CryptoCurrency', CryptoCurrencySchema);
答案 0 :(得分:1)
从您的代码示例中,您似乎将子文档保存为引用,这意味着一旦更新子文档,您只需要为它调用.save()而不是父文档。< / p>
如果要将文档保存为子模式,则更新子文档后,只能为父文档调用.save(),并且它也会保留子文档。
来自文档:
子文档享有与普通文档相同的所有功能。该 唯一不同的是,他们没有单独保存,他们是 保存顶级父文档时保存。