Scenario Description
When a record needs to be updated, first check whether the name of this record already exists in 集合Collection
(excluding itself).
Logical direction
Step 1: Find yourself in the set
Step 2: Find yourself in the set according to your name
Step 3: Judge Step 1的_id
and Step 2的_id
Whether it matches
Step 4: If the two _ids do not match, it will prompt "name already exists"; otherwise, complete the record update
The problem we are encountering now is: Step 1的_id
and Step 2的_id
cannot match.
Attach my code
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"]);
});
}
});
Maybe there is something wrong with my thinking, or maybe there is something wrong with my code. I need to ask experts for guidance...
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