如何使用mongodb,mongoose按特定属性插入或更新对象?

时间:2016-01-02 08:34:33

标签: node.js mongodb mongoose

我想通过mongodb插入或更新mongodb对象。为了解释,我准备了如下样本。我想在propList中使propA和child对象唯一。

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);
    }
);

但是这段代码不能正常工作。在我运行此代码两次后,将插入重复的对象,而不是更新。

> 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 }

我认为如果我把这个猫鼬程序分成多个程序,就有可能。但有没有办法通过一个方法调用插入/更新?

环境

  • mongodb v3.2.0
  • mongoose v4.3.4

1 个答案:

答案 0 :(得分:0)

如果您想保证不会插入重复项,请考虑使用唯一索引。链接到文档:https://docs.mongodb.org/manual/reference/method/db.collection.update/

相关问题