我遇到的问题是我认为是猫鼬中变量的范围。我的代码是这样的:
var blogUserId;
blogs.forEach(function(blog, index) {
User.findOne({'username': blog.username}, function(err, user) {
blogUserId = user._id;
console.log(blogUserId);
});
console.log(blogUserId);
Blog.find({'title': blog.title}, function(err, blogs) {
if (!err && !blogs.length) {
console.log(blogUserId);
Blog.create({title: blog.title, author: blogUserId, body: blog.body, hidden: blog.hidden});
}
if (err) {
console.log(err);
}
});
});
这是仅用于开发的种子文件的一部分,但我很困惑为什么它不能正常工作。 blogs
只是要加载到集合中的对象数组。我搜索了所有类似的答案,但我还没有找到一个可以解释这个问题的正确答案。
答案 0 :(得分:1)
调用blogUserId
时未设置Blog.find()
。你必须以不同的方式嵌套它,如下所示:
var blogUserId;
blogs.forEach(function(blog, index) {
User.findOne({'username': blog.username}, function(err, user) {
blogUserId = user._id;
console.log(blogUserId);
Blog.find({'title': blog.title}, function(err, blogs) {
if (!err && !blogs.length) {
console.log(blogUserId);
Blog.create({title: blog.title, author: blogUserId, body: blog.body, hidden: blog.hidden});
}
if (err) {
console.log(err);
}
});
});
});
我尚未对其进行测试,因此我不确定您的代码中是否存在其他错误,但肯定是您调用Blog.find
预期blogUserId
的问题可能在User.findOne
回调中设置之前设置。
可以使用命名回调以更易读的方式编写它。
在Node中工作时,您需要记住您在异步环境中工作。