【问题标题】:Can't update Mongoose subdocument property无法更新 Mongoose 子文档属性
【发布时间】:2015-11-08 18:57:19
【问题描述】:

使用以下代码行我可以更新给定的事务(文档),但是当我尝试更新其子文档的属性时,给定的值不会持久化。

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

【问题讨论】:

  • 您使用的是哪个版本的 Node 和 Mongoose?
  • iojs 版本 3.0.0,猫鼬 4.0.6
  • 您能否更新您的问题以显示您的架构定义

标签: node.js mongodb mongoose


【解决方案1】:

从您的代码示例看来,您正在将子文档保存为引用,这意味着一旦您更新了子文档,您只需要为它调用 .save() 而不是父文档。

如果您将文档保存为子架构,则在更新子文档后,您可以仅为父文档调用 .save(),它也会保留子文档。

来自文档:

子文档享有与普通文档相同的所有功能。这 唯一的区别是 它们不是单独保存的,而是 保存其顶级父文档时保存。

http://mongoosejs.com/docs/subdocs.html

【讨论】:

  • 好的,这听起来很准确,我现在应该有时间来测试一下。查看我自己的模型,它似乎是作为参考而不是子模式构建的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 2021-02-06
  • 2017-03-17
  • 2021-12-23
  • 2015-07-12
相关资源
最近更新 更多