猫鼬 - 如何将文档属性设置为另一个文档
问题描述:
我想通过为嵌入式文档创建一个单独的模型,验证它,如果验证成功,将其设置为主文档的属性来伪造非数组嵌套文档。猫鼬 - 如何将文档属性设置为另一个文档
在POST/API /文件路径我做格兰以下:
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())...但是我现在无法自己想象。
答
看起来答案是使用回调来设置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);
}
})
});
答
看起来像author.validate
是异步的,因此您的console.log(document);
语句在执行document.author
的回调之前执行。您需要将取决于document.author
的处理置于回调中。
有没有一种办法做没有嵌套回调?中间件也许? – ragulka 2012-08-03 12:57:33
是的,我认为使用Mongoose中间件将是一个很好的方式去这里。 – JohnnyHK 2012-08-03 13:02:35
嗯,它似乎即使我可以'console.log(document.author)'使用回调时,似乎'console.log(文档)'不包括作者...... – ragulka 2012-08-03 19:18:25