账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Mongoose 更新 ref 和 populate ref的问题
    32
    0

    环境:

    • Mongodb 3.6.3
    • mongoose: 5.2.5
    • nodeJS: 8.X

    描述:

    • 模拟博客系统,有两个collection( articles / comments), schema 如下
    // article model
    const ArticleSchema = new Schema({
      title: String,
      author: String,
      content: String,
      lastModified: {type: Date, default: Date.now()},
      // comments collections refs
      comments: [{type: Schema.Types.ObjectId, ref: 'comments'}],
      meta: {
        tags: {type: Array, default: []},
        votes: {type: Number, default: 0}
      }
    });
    // comments model
    const CommentSchema = new Schema({
      // DBref to article collection
      article: {
        type: Schema.Types.ObjectId,
        ref: 'article'
      },
      // For unlogined user
      tempNick: String,
      // For future logined user
      status: Schema.Types.ObjectId,
      content: String,
      replies: [
        {
          // name for both logined & unlogined
          name: '',
          content: String,
          createdTime: {
            type: Date,
            default: Date.now()
          }
        }
      ],
      createdTime: {
        type: Date,
        default: Date.now()
      }
    });

    article 和 comment 是一对多的关系,因此在发布评论的方法上我是这样做的:

    // Write comment
    exports.postComment = function(req, res) {
      let request;
      let aid;
      console.log(chalk.green('WRITING COMMENTS'));
      request = req.body;
      request._id = new mongoose.Types.ObjectId();
      aid = req.params.aid;
      let comment = new Comment(request)
      comment.save(function(err) {
        if (err) {
          errCallback(err, res);
        } else {
          // let article = new Article({
          //   comments: comment._id
          // })
          Article.findByIdAndUpdate(aid, {$push: {comments: request._id}}, function (err, com) {
            if (err) {
              errCallback(err);
            }
            console.log('----------');
          })
          postSuccessCallback('post comment success', res);
        }
      })
    }

    嗯,结果是可以写入成功的,写入两次并通过mongoshell查询发现该article文档内的comments数组字段有两个内容
    [ObjectId(*************),ObjectId(****************)]

    但是,通过组织Mongoose来进行查询却返回undefined:

    // Query for comment
    // Params: { offset / limit / sortBy }
    exports.getComments = function(req, res) {
      let count;
      let data;
      let { offset, limit, sortBy } = req.query;
      let { aid } = req.params
    
      // Get Total count
      Comment.estimatedDocumentCount(function(err, num) {
        if (err) {
          errCallback(err, res);
          return
        }
        count = num;
      });
      offset = Number(offset);
      limit = Number(limit);
      console.log('aid', aid);
      Article.findById(aid).
      populate('comments').
      // skip(offset).
      // limit(limit).
      // sort(dueSortby(sortBy)).
      exec((err, comment) => {
        console.log('execed!', comment)
        data = comment;
        getCountCallback(data, count, res);
      });
    }

    篇幅啰嗦,恐怕丢掉细节,如有解答望不吝告知!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部