当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - 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/

分享给朋友:
您可能感兴趣的文章:
随机阅读: