findOne() 的 Mongoose (express, node, mongo) 作用域问题
Mongoose (express, node, mongo) scope issue with findOne()
我对 mongoose 中变量的范围有疑问。我的代码是这样的:
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
只是一个要加载到集合中的对象数组。我搜索了所有类似的答案,但没有找到可以解释这一点的正确答案。
调用 Blog.find()
时未设置您的 blogUserId
。你必须以不同的方式嵌套它,像这样:
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 中工作时,请记住您是在异步环境中工作。
我对 mongoose 中变量的范围有疑问。我的代码是这样的:
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
只是一个要加载到集合中的对象数组。我搜索了所有类似的答案,但没有找到可以解释这一点的正确答案。
调用 Blog.find()
时未设置您的 blogUserId
。你必须以不同的方式嵌套它,像这样:
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 中工作时,请记住您是在异步环境中工作。