node.js - mongoose如何update某属性的ref
阿神
阿神 2017-04-17 16:07:58
0
2
785

参见mongoose

两集合schema如下:

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

fans中的一个person取消了对story的喜好(fans的理解不知道对不对)
那么story.fans是数组,可以delete掉该person的数据
这个感觉还比较容易update

如果一个personstory不正确,同时story集合中并不存在该person的正确story
那么是removepersonfield:stories吗?
还是能够将该personfield:stories这个ObjectId类置空?

希望各位能够提供一些建议?

阿神
阿神

闭关修行中......

reply all(2)
刘奇

If I understand correctly, how to handle it depends on the needs of the application.

However, the second situation you assumed will usually not occur if the populate is normal.

For reference.

Ty80

When paying attention

Add Stroy to Person ($addToSetremove duplicates, $push)$addToSet去重, $push)

    Person.update({
            _id: persionId
        }, {
         $addToSet : { stories: storyId }
        }, function(err, raw)

添加 fans $addToSet(去重), $push(不去重)

Story.update({
        _id: storyId
    }, {
     $addToSet : { fans: persionId }
    }, function(err, raw)

取消关注

删除 Person ($pull)

    Person.update({
            _id: persionId
        }, {
         $pull : { stories: storyId }
        }, function(err, raw)

删除 fans ($pull

Story.update({
        _id: storyId
    }, {
     $pull : { fans: persionId }
    }, function(err, raw)
Add fans $addToSet (remove duplicates), $push (do not remove duplicates)🎜 rrreee 🎜Unfollow🎜 🎜Delete Person ($pull)🎜 rrreee 🎜Delete fans ($pull)🎜 rrreee
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!