简体   繁体   中英

How to insert or update objects by specific properties with mongodb, mongoose?

I want to insert or update mongodb objects by mongodb. For explanation, I prepared a sample like below. I want to make propA and child objects in propList unique.

var test = new mongoose.Schema({
  propA  : String, // unique
  propList : [{
              name  : String, // unique
              propB : String,
              propC : String
            }]
});
var Test = mongoose.model('Test', test);

var newTest = new Test({
  propA: 'newPropA',
  propList: [{ name: 'Jef' }]
});

// Test.update( // not working correctly too
Test.findOneAndUpdate(
    {propA: 'HOGE'},
    newTest,
    {upsert: true}, 
    function(err, result) {
      if(err) console.log('err:', err);
    }
);

But this code doesn't work correctly. After I ran this code twice, duplicated objects are inserted, not updated.

> db.tests.find()
{ "_id" : ObjectId("5687894f50ce0fb4fc2f7b26"), "propA" : "newPropA", "propList" : [ { "name" : "Jef", "_id" : ObjectId("5687894f50ce0fb4fc2f7b27") } ], "__v" : 0 }
{ "_id" : ObjectId("56878951c7fd4fbdfca08645"), "propA" : "newPropA", "propList" : [ { "name" : "Jef", "_id" : ObjectId("56878951c7fd4fbdfca08646") } ], "__v" : 0 }

I think if I separate this mongoose procedure to multiples ones, it could be possible. But are there any ways to insert/update by one method call?

environments

  • mongodb v3.2.0
  • mongoose v4.3.4

Please consider using unique indexes if you want to guarantee that no duplicates will be inserted. Link to the doc : https://docs.mongodb.org/manual/reference/method/db.collection.update/

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