我是Mongoose的新手,我的模式中有一个数组,它是如下所示的嵌套文档:
const userSchema = new Schema({
username: String
friends: [friendsSchema],
});
const friendsSchema = new Schema({
name: { type: String, unique: true },
});
假设我想将一位朋友添加到特定用户,我需要执行以下操作:
- 判断用户id是否有效
- 判断数据库中是否存在该用户ID
- 如果用户存在,判断他是否已经有一个使用该名字的朋友
- 如果他不把一个新朋友推入朋友阵营
我最初认为,一旦我获得了用户,我可以简单地在user.Friends数组上执行Foreach循环来验证该朋友的存在.然而,事实证明,mongoose Arrays的行为与常规的JavaScript数组不同.这非常令人沮丧,因为这意味着我需要构造一个复杂的查询,这可能会导致额外的数据库读取,而不是直接访问用户并判断来自User对象的所需信息.因此,我想出了以下实现:
let { name, userId } = req.body;
try {
//check if userId is a valid mongoose objectId
if (!mongoose.Types.ObjectId.isValid(userId)) {
res.status(404).json({ error: "invalid user id" });
}
// get the user
let user = await userModel.findById(userId);
if (!user) {
res.status(404).json({ error: "user not found" });
}
let user = user.friends.foreach(friend =>{
if (friend.name === name)
{
res.status(404).json({error: "friend already added to user"});
}
});
user.friends.push({ name});
user.save();
res.status(200).json(user);
-
有没有可能在一个查询中完成前面的所有步骤,就像一个数据库读取可以执行所有操作一样?
-
在Mongoose上有一个不同的数组类型的合理性是什么?
PS:这不是关于如何推送和保存到数组的重复问题