node.js - Mongoose 嵌套文档更新失败?

标签 node.js mongodb mongoose

如果我有嵌套文档,如何在 Mongoose 中更新该嵌套文档中的字段?

我使用我能找到的所有可用资源仔细研究了这个问题,甚至更改了我的测试代码以匹配 Stackoverflow 上关于此的类似已回答问题,但我仍然无法弄清楚。这是我的架构和模型、代码和 Mongoose 调试输出。我无法理解我在这里做错了什么。

var mongoose = require('mongoose')
  , db = mongoose.createConnection('localhost', 'test')
  , assert = require("node-assert-extras");

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

db.once('open', function () {
  // yay!
});
mongoose.set('debug', true);

var PDFSchema = new Schema({
      title     : { type: String, required: true, trim: true }
})

var docsSchema = new Schema({
     PDFs           : [PDFSchema] 
});

var A = db.model('pdf', PDFSchema);
var B = db.model('docs', docsSchema);

function reset(cb) {
  B.find().remove();
  // create some data with a nested document A
  var newA = new A( { title : "my title" })
  var newB = new B( { PDFs: newA});
  newB.save();
  cb();
}

function test1( ) {
    reset(function() {
        B.findOne({}, 'PDFs', function(e,o)
        {
            console.log(o);
            pdf_id = o.PDFs[0]._id;
            console.log("ID " + pdf_id);
            B.update(
                { 'pdfs.pdf_id': pdf_id }, 
                { $set: { 
                    'pdfs.$.title': 'new title'
                }}, function (err, numAffected) { 
                    if(err) throw err;
                    assert.equal(numAffected,1);  //KA Boom!
                }
            );  

        });
    });
}

test1();

/*
$ node test2.js
Mongoose: docs.remove({}) {}  
Mongoose: docs.findOne({}) { fields: { PDFs: 1 }, safe: true }  
Mongoose: docs.insert({ __v: 0, PDFs: [ { _id: ObjectId("50930e3d0a39ad162b000002"), title: 'my title' } ], _id: ObjectId("50930e3d0a39ad162b000003") }) { safe: true }  
{ _id: 50930e3d0a39ad162b000003,
  PDFs: [ { _id: 50930e3d0a39ad162b000002, title: 'my title' } ] }
ID 50930e3d0a39ad162b000002

assert.js:102
  throw new assert.AssertionError({
        ^
AssertionError: 0 == 1



*/

最佳答案

您没有在 B.update 调用中使用正确的字段名称。应该是这样的:

B.update(
    { 'PDFs._id': pdf_id },           // <== here
    { $set: {
        'PDFs.$.title': 'new title'   // <== and here
    }}, function (err, numAffected) {
        if(err) throw err;
        assert.equal(numAffected,1);
    }
);

您还应该修复您的 reset 函数,使其在 save 完成之前不调用其回调:

function reset(cb) {
  B.find().remove();
  // create some data with a nested document A
  var newA = new A( { title : "my title" })
  var newB = new B( { PDFs: newA});
  newB.save(cb);  // <== call cb when the document is saved
}

关于node.js - Mongoose 嵌套文档更新失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187486/

相关文章:

node.js - 我是否必须在 axios 配置中声明数据

javascript - 在 db.open() 回调中使用导出 - mongoose/express

javascript - EntityMetadataNotFound : No metadata for "Task" was found - NestJS

javascript - 另一个 javascript 函数对象问题 - 比使用 toString() 更优雅的方法

javascript - 在 typescript 中导出默认值后实例化对象返回错误

ruby - 我可以通过 ruby​​ 驱动程序访问 mongo 的 geoNear 功能吗?

java - 错误 java.lang.NoClassDefFoundError : com/mongodb/MongoClient

mongodb - mongodb日志中的 "locks(micros) w:16035"和 "locks(micros) r:10051"是什么

javascript - S3 替代方案,允许在不缓冲的情况下上传流文件

node.js - 如何使用原子查询更新 Mongoose 中另一个子文档内的子文档?