猫鼬不返回值
Mongoose not returning value
函数 GetByName 有效,因为结果正确打印到控制台,但我没有返回值。谁能告诉我哪里出错了。
supportDoc.tagId = GetByName(item.tagName); <-- returns undefined
function GetByName(name) {
model.Shared_SupportTag.findOne({name : name}).exec(function (err, result) {
if (result.length === 0) {
console.log('Not Found')
} else {
console.log(result._id);
return (result._id)
};
});
更新:
复制了 victorkohl 的建议,仍然出错。
该值正在通过,但仍然出现错误。这是智能感知、控制台和 "foreign key" 属性.
已解决:
victorskohl 是正确的,我只需要在最后调用 GetByName 函数,并在其中包含保存方法。
model.Shared_SupportDoc.find({}).exec(function (err, collection) {
var supportDocs = require('../../data/_seed/support/supportDocs.json');
if (collection.length === 0) {
supportDocs.forEach(function (item) {
....
supportDoc.icon = item.icon;
supportDoc.likeCount = item.likeCount || 7;
GetByName(item.category, function(tagId) {
supportDoc.categoryId = tagId;
supportDoc.save(function (err) {
if (err) {
console.log(supportDoc.categoryId)
console.log('Error: ' + err);
} else {
console.log('Support Doc Seed Complete');
}
});
});
您正在尝试使用异步方法执行同步任务。 .exec()
上传递的函数是异步执行的,因此,您的函数 GetByName returns 在该函数执行之前(没有值,因此是 undefined
结果)。
您还应该使 GetByName 函数也 运行 异步,例如:
GetByName(item.tagName, function(tagId) {
supportDoc.tagId = tagId;
});
function GetByName(name, next) {
model.Shared_SupportTag.findOne({name : name}).exec(function (err, result) {
if (!result) {
console.log('Not Found');
next();
} else {
console.log(result._id);
next(result._id);
}
});
}
函数 GetByName 有效,因为结果正确打印到控制台,但我没有返回值。谁能告诉我哪里出错了。
supportDoc.tagId = GetByName(item.tagName); <-- returns undefined
function GetByName(name) {
model.Shared_SupportTag.findOne({name : name}).exec(function (err, result) {
if (result.length === 0) {
console.log('Not Found')
} else {
console.log(result._id);
return (result._id)
};
});
更新:
复制了 victorkohl 的建议,仍然出错。
该值正在通过,但仍然出现错误。这是智能感知、控制台和 "foreign key" 属性.
已解决:
victorskohl 是正确的,我只需要在最后调用 GetByName 函数,并在其中包含保存方法。
model.Shared_SupportDoc.find({}).exec(function (err, collection) {
var supportDocs = require('../../data/_seed/support/supportDocs.json');
if (collection.length === 0) {
supportDocs.forEach(function (item) {
....
supportDoc.icon = item.icon;
supportDoc.likeCount = item.likeCount || 7;
GetByName(item.category, function(tagId) {
supportDoc.categoryId = tagId;
supportDoc.save(function (err) {
if (err) {
console.log(supportDoc.categoryId)
console.log('Error: ' + err);
} else {
console.log('Support Doc Seed Complete');
}
});
});
您正在尝试使用异步方法执行同步任务。 .exec()
上传递的函数是异步执行的,因此,您的函数 GetByName returns 在该函数执行之前(没有值,因此是 undefined
结果)。
您还应该使 GetByName 函数也 运行 异步,例如:
GetByName(item.tagName, function(tagId) {
supportDoc.tagId = tagId;
});
function GetByName(name, next) {
model.Shared_SupportTag.findOne({name : name}).exec(function (err, result) {
if (!result) {
console.log('Not Found');
next();
} else {
console.log(result._id);
next(result._id);
}
});
}