如何在Mongoose中存储在集合中的数组中调用"findOne"函数



集合的model

const clientInfo = {
uniqueID: {
type: String,
required: true,
},
firstName: {
type: String,
required: true,
},
lastName: String,
email: {
type: String,
required: true,
},
countryCode: String,
phone: String,
status: {
type: String,
required: true,
},
addedOn: {
date: String,
time: String,
},
};

这个模型存储在另一个模型中

const userClient = {
userID: {
type: String,
required: true,
},
clients: [clientInfo],
};

现在,我想将客户的电子邮件与我收到的请求正文进行比较。我现在是这样做的:

await UserClient.findOne(
{ userID: validUser.userID },
async (err, clientList) => {
if (clientList) {
//Check for duplicate client
await clientList.findOne(
{ email: req.body.email },
(err, duplicateClient) => {
if (duplicateClient) {
return res.status(400).send(`Client already exists!`);
} else {
clientList.clients.push(client);
clientList.save();
const response = {
statusCode: 200,
message: "Client added!",
client: client,
};
res.send(response);
}
}
);
} else {
const newList = new UserClient({
userID: validUser.userID,
clients: client,
});
newList.save();
const response = {
statusCode: 200,
message: "Client added!",
client: client,
};
res.send(response);
}
}
);
});

但是我得到了一个错误UnhandledPromiseRejectionWarning: TypeError: clientList.findOne is not a function

我现在所做的是,找到一个具有特定userID的集合,如果我匹配,我想将数组中的所有对象与我在请求体上收到的电子邮件进行比较。目前,如果它在UserClient.findOne中没有找到任何匹配,一切都很顺利,但如果我在UserFind.findOne中有匹配,并且我想在数组中调用类似的方法,我会得到错误。

如何消除此错误?

提前谢谢。

试试这个

await UserClient.findOne(
{ userID: validUser.userID,'clients.email': req.body.email },
async (err, clientList) => {
if(err){
//throw error here
}
console.log(clientList)
})

纠正了一些问题,

  • 通过id查找用户,检查是否找到用户,然后在循环中的电子邮件基础上查找客户端,如果找到,则返回客户端存在,否则保存到用户文档
  • 如果找不到客户端,则添加新用户和客户端
await UserClient.findOne(
{ userID: validUser.userID },
async (err, User) => {
// FIND CLIENT
if (User) {
let clientExists = false;
for (let c in User.clients) {
if (User.clients[c].email == req.body.email ) clientExists = true;
}
// ADD CLIENT
if (clientExists) {
User.clients.push(client);
User.save();
return res.send({
statusCode: 200,
message: "Client added!",
client: client,
});
}
// CLIENT EXISTS 
else {
return res.status(400).send(`Client already exists!`);
}
} 
// ADD NEW USER AND CLIENTS
else {
const newList = new UserClient({
userID: validUser.userID,
clients: client,
});
await newList.save();
return res.send({
statusCode: 200,
message: "Client added!",
client: client
});
}
}
); 

我还没有测试过这个代码,如果你遇到任何问题,请告诉我。

最新更新