场景描述
当某条记录需要更新时,先查询这条记录的名称在集合Collection
中是否已存在(排除本身)。
逻辑方向
Step 1:在集合中查找自己
Step 2:根据自己的名称在集合中查找
Step 3:判断 Step 1的_id
与 Step 2的_id
是否匹配
Step 4:若两者_id不匹配,则提示“名称已存在”;反之,完成记录更新
现在遇到的问题是: Step 1的_id
与 Step 2的_id
匹配不上。
附上我的代码
var _q = req.body, _qId = mongoose.Types.ObjectId(_q["_id"]);
groups.findById(_qId,function (err,data) {
if(err){
res.json({code: 404, msg: "Error"});
}else{
groups.findOne({name:_q["name"]},null).exec(function (_err,_data) {
console.log(data["_id"] == _data["_id"]);
});
}
});
可能是我的思路有问题,也可能是我的代码有问题,要请各路高手指点...
Let me sort out your code. To be honest, I don’t like your coding style very much, because all kinds of unnecessary variable declarations lead to poor code expression
First of all I assume you are using express because you use req.body
That is to say, two values are passed in your post request, one is _id and the other is name. You use the two values to search the database respectively, so you get two search results (two doc), and then you try to compare whether the doc obtained through _id search and the doc searched through name are the same thing (of course comparing _id is to compare whether they are the same doc)
Based on the conditions you gave, I first guessed whether the _id and name in the req.body you gave match. Maybe they come from two different docs? Or maybe there are two docs with the same name in your database, so the doc obtained through name search and the doc obtained through id search are not the same?
You can try to print docById and docByName before the final console.log, and post your mongoose scheme to take a look. This way we at least know what kind of database you are searching for
This uses findOne, which will only return one record. Maybe there are multiple values with the same name in the library, and the one you took out happens to be different from the one you want
The method has been found: convert the _id obtained in Step 1 using
String()
.Full code