Home  >  Q&A  >  body text

node.js - mongoose如何update某属性的ref

参见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类置空?

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

阿神阿神2761 days ago787

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 16:09:58

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 16:09:58

    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

    reply
    0
  • Cancelreply