[英]Mongodb/Mongoose multiple insert/update with conditions
这是我的访客模式:
_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.
data.map(doc => {
Visitor.findOneAndUpdate(
{_post: doc._post},
{$addToSet: {_visitors: {$each: doc._visitors}}}
)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.