Mongoose - 如何将文档属性设置为另一个文档

时间:2012-08-03 12:37:20

标签: node.js mongodb express mongoose

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

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

似乎Mongoose没有“设置”模式中未定义的模型的任何属性。由于我的作者是一个对象,我不得不将Schema中的author字段设置为Mixed,就像这样。

以下代码有效:

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