Mongodb / Mongoose多次插入/更新条件

时间:2018-02-01 19:53:19

标签: node.js mongodb mongoose

这是我的访客架构:

_post: { type: Schema.Types.ObjectId, ref: 'posts' },    
_visitors: [{
   _user: { type: Schema.Types.ObjectId, unique: true, ref: 'users' },
   createdAt: { type: Date, default: Date.now }
}]

我想要在以下条件下插入或更新数据库。 数据(约1000个文档):

[
    {
        "_post": "5a492315610cba521e74d0c5",
        "_visitors": [
            {
                "_user": "59a5c77367193d146bd5970b"
            }
        ]
    },
    {
        "_post": "5a492326610cba521e74d0cc",
        "_visitors": [
            {
                "_user": "59a5c77367193d146bd5970b"
            }
        ]
    },
    // ...
]

条件:

1) Create new doc if _post does not exist.
2) Push _user to _visitors if it hasn't this _user
3) If _post exist and it has _user in _visitor, does nothing.

1 个答案:

答案 0 :(得分:0)

data.map(doc => {
   Visitor.findOneAndUpdate(
       {_post: doc._post},
       {$addToSet: {_visitors: {$each: doc._visitors}}}
   )
})