Mongoose更新ref对象?

时间:2016-04-15 11:19:30

标签: javascript node.js mongodb mongoose

很抱歉我的英语不好 我使用node.js + express.js + mongoose.js 我有mongoose的这个模式为组:

var groupSchema = new mongoose.Schema({
    name: String,
    users: [{type: mongoose.Schema.ObjectId, ref: 'User'}],
    posts: [{type: mongoose.Schema.ObjectId, ref: 'Post'}]
});

这个架构给用户:

var userSchema = new mongoose.Schema({
  login:    { type: String, unique: true, lowercase: true },
  password: String,
  unread:   [{type: mongoose.Schema.ObjectId, ref: 'Post'}]      
});

群组包含与此群组相关的用户列表以及与此群组相关的帖子列表 我想要实现的目标:
Group1有用户MikeJohnJane;
当用户Mike创建新帖子时:1)我找到当前组并选择与该组相关的用户(Group1和用户MikeJohnJane);

2)对于用户JohnJane,我必须在unread字段中设置已创建的帖子。 (让这个知道,哪个帖子用户还没有读过) 这是对的吗?如果是,我如何在ref文档中更新此未读字段?
我试图这样做:
例如:该组的网址:http://localhost:3000/group/first

  app.get('/group/:name', groups.getGroupPage);

  app.post('/group/:name', posts.postCreate);

Posts.js

var Group = require('../models/group');
var User = require('../models/user');
var Post = require('../models/post');

        exports.postCreate = function(req, res) {
         var post = new Post({
            title: req.body.p_title,
            content: req.body.p_content,
            author: req.user
         });
         Group
                  .update({ name: req.params.name }, {upsert:true}, { "$push": { "users.$.unread": post._id } })
                  .populate('users')
                  .exec(function(err,group) {
                       if (err) res.json(err)
                       console.log(group);
                    }
                  );
        }

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你的编码风格与我的有点不同,但我将采取的方式如下:

exports.postCreate = function(req, res) {
  //Create a new post
  var newPost = new Post({
    title: req.body.p_title,
    content: req.body.p_content,
    author: req.user
  });

  //Save the new post
  newPost.save(function(err) {
    if (err) {
      res.json(err);
    }
  });

  //Find the group with the name and populate the users field
  Group.findOne({ name: req.params.name })
    .populate('users')
    .exec(function(err, group) {
      if (err) {
        res.json(err);
        console.log(group);
      }
      if (group) {
        //If group is found loop through the users
        for (var i = o; i < group.users.length; i++) {
          //Check if the current user is somebody else as the author
          if (group.users[i]._id != req.user._id) {
            //Push and save the new post to every user in the group
            //We push the _id of the post because we are using references
            group.users[i].unread.push(newPost._id);
            group.users[i].save(function(err) {
              if (err) {
                throw err;
              }
            });
          }
        }
      } else {
        //Do what you need to do if group hasn't been found
      }
    });
};

此代码假定您的req.user字段已填充为用户架构。

此代码未经测试。所以请调试它。 :)