【问题标题】:Mongoose - how to set document property to be another documentMongoose - 如何将文档属性设置为另一个文档
【发布时间】:2016-04-08 02:54:33
【问题描述】:

我试图通过为嵌入文档创建一个单独的模型并对其进行验证来伪造非数组嵌套文档,如果验证成功,则将其设置为主文档的属性。

在 POST /api/document 路由中,我正在执行以下操作:

var document = new DocumentModel({
  title: req.body.title
});

var author = new AuthorModel({
  name: req.body.author.name
});

author.validate( function( err ) {
  if (!err) {
    document.author = author.toObject();
  } else {
    return res.send( err, 400 );
  }
});

console.log( document );

但它似乎不起作用 - 控制台打印出没有作者的文档。我可能在这里遗漏了一些非常明显的东西,也许我需要做一些嵌套回调,或者我需要使用特殊的设置方法,比如 document.set('author', author.toObject())...但是我现在无法独自想办法。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    看起来author.validate 是异步的,因此底部的console.log(document); 语句在您设置document.author 的回调之前执行。您需要将依赖于 document.author 设置的处理放在回调中。

    【讨论】:

    • 有没有办法在没有嵌套回调的情况下做到这一点?也许是中间件?
    • 是的,我认为使用 Mongoose 中间件是一个不错的选择。
    • 嗯,虽然我在使用回调时可以console.log(document.author),但似乎console.log(document) 还没有包含作者...
    【解决方案2】:

    看起来答案是使用回调来设置 document.author 并在 Schema 中定义作者。

    就像@JohnnyHK 指出的那样,我无法使用我的原始代码将文档记录到控制台,因为 author.validate 是异步的。因此,解决方案是将 console.log (可能还有 document.save() 进一步包装在 author.validate() 的回调中

    Mongoose 似乎也没有为模式中未定义的模型“设置”任何属性。由于我的作者是一个对象,所以我必须将 Schema 中的作者字段设置为混合,就像这样。

    以下代码有效:

    var DocumentModel = new Schema({
        title: { type: String, required: true },
        author: {}      
    });
    var AuthorModel = new Schema({
        name: { type: String, required: true }
    });
    app.post("/api/documents", function(req, res) {
        var document = new DocumentModel({
            title: req.body.title
        });
        var author = new AuthorModek({
            title: req.body.author.name
        });
        author.validate( function( err ) {
            if (!err) {
                document.author = author;
                docment.save( function( err ) {
                    ...
                });
            } else {
                return res.send( err, 400 );
            }
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 2015-03-23
      • 2016-12-14
      相关资源
      最近更新 更多