简体   繁体   中英

How to find a document by an field other than _id using mongo/mongoose

Background: I must create or update an document based on post request that I have zero control over. I'm calling the function updateOrCreate()

Question:

How can I properly find a document by an field called nuid without using _id in mongo/mongoose


example payload:

curl -H "Content-Type: application/json" -X POST -d '{"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}}' http://localhost:9000/api/things

thing.controller:

exports.updateOrCreate = function(req, res) {
 //Thing.findByNuid() will not work but it will explain what i'm trying to accomplish
 /**
 Thing.findByNuid(req.body.participant.nuid, function (err, thing) {

  if (err) { return handleError(res, err); }
  if(!thing) {
    Thing.create(req.body.participant, function(err, thing) {
    if(err) { return handleError(res, err); }
  });
 }
  var updated = _.merge(thing, req.body.participant);
  updated.save(function (err) {
    if (err) { return handleError(res, err); }

  });
});
**/
 //this block will fetch all the things that have nuids but that seems really heavy and awful practice
  Thing.find({'nuid':req.body.participant.nuid}, function(err, thing){
     console.log(thing);
  });
  // This block is here to communicate this will create a new thing as expected.
  Thing.create(req.body.participant, function(err, thing) {
    if(err) { return handleError(res, err); }

  });
}

Schema

var ThingSchema = new Schema({
  nuid: String
});

UPDATE:

 var query = {"nuid": req.body.participant.nuid};
 var update = {nuid: 'heyyy'};

  Thing.findOneAndUpdate(
      query,
      update,
      {upsert: true},
      function(err, thing){
        console.log(thing, "thing");
        console.log(err, "err");
      }
  );

I would use findOneAndUpdate first and then based on the result do an insert . findOneAndUpdate use mongoDB findAndModify command.

You should also look at new & upsert options of it which would create a document if not found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM