Mongoose 猫鼬不返回值
函数GetByName起作用,因为结果正确地打印到控制台,但我没有返回值。谁能告诉我哪里出了问题Mongoose 猫鼬不返回值,mongoose,Mongoose,函数GetByName起作用,因为结果正确地打印到控制台,但我没有返回值。谁能告诉我哪里出了问题 supportDoc.tagId = GetByName(item.tagName); <-- returns undefined function GetByName(name) { model.Shared_SupportTag.findOne({name : name}).exec(function (err, result) { if (result.length ===
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)
};
});
您正在尝试使用异步方法执行同步任务。传递给
.exec()
的函数是异步执行的,因此,函数GetByName在该函数执行之前返回(没有值,因此未定义的结果)
您应该使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);
}
});
}
if(result.length==0){^TypeError:无法读取null.name参数的属性'length'在functionfixed中没有值。如果找不到结果,result
没有方法length
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);
}
});
}