Mongoose更新ref对象

Mongoose update ref objects?

本文关键字:对象 ref 更新 Mongoose      更新时间:2023-09-26


很抱歉我的英语不好
我使用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文档中的未读字段?
我试着这样做:
例如:组的url: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);
                    }
                  );
        }

谢谢你的帮助。

您的编码风格与我的有点不同,但我的做法如下:

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字段被填充为User模式。

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