How does MongoDB verify that a value already exists when updating records

  mongodb, question

Scene description
When a record needs to be updated, first query the name of the record in theCollectionDoes the already exist in (exclude itself).

Logical direction
Step 1: Find yourself in the collection
Step 2: Find in the collection according to your own name
Step 3: JudgmentStep 1 _idAndThe _id of Step 2Does it match
Step 4: If the two _ IDs do not match, it will prompt “Name already exists”; On the contrary, the record update is completed

The problem now is:Step 1 _idAndThe _id of Step 2It doesn’t 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 my code. Please ask all the experts for advice. …

Let me tidy up your code. To be honest, I don’t like your code style very much, because all kinds of unnecessary variable declarations make the code look bad.

First, let me assume that you are using express because you are using req.body.

//What is this definition for?  Is it to prevent your boss from firing you so others can't understand the code?
 //var _q = req.body, _qId = mongoose.Types.ObjectId(_q["_id"]);
 
 groups.findById(req.body._id, function (err, docById) {
 if(err){
 res.json({code: 404, msg: "Error"});
 }else{
 groups.findOne({name:req.body.name}, null)
 .exec(function (_err, docByName) {
 console.log(docById._id == docByName._id);
 });
 }
 });

That is to say, you send two values in a post request, one is _id and the other is name. you use the two values to search the database respectively, and then you get two search results (two doc). then you try to compare whether doc obtained through _id search and doc searched through name are the same thing (comparing _id is, of course, comparing whether doc is the same doc or not)

Based on the conditions you have given, I first guess if the _id and name in the req.body you have given match, perhaps they are originally from two different doc? Or do you really have two docs with the same name in your database, then 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 first before the final console.log, and paste your mongoose scheme to have a look. in this way, we at least know what kind of database you are searching for.