Mongoose将一个集合分配给另一个

时间:2016-12-27 11:39:08

标签: javascript node.js mongodb mongoose mongoose-schema

我尝试在用空帖创建用户后向用户集合添加帖子。我已尝试使用populate但没有成功..非常感谢任何帮助。



// Post Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
 
const UserModel = require('./user-model');
 
let PostSchema = new Schema({
  author: {
    ref: 'users',
    type: Schema.Types.ObjectId
  },
  content: String,
  description: String,
  date: {
    default: new Date(),
    type: Date
  },
  title: String,
  updatedAt: {
    default:  new Date(),
    type: Date
  }
});

let PostModel = mongoose.model('posts', PostSchema);
module.exports = PostModel;
// User Model 
 
const mongoose = require('mongoose');
const { Schema } = mongoose;
 
const PostModel = require('./post-model');
 
let UserSchema = new Schema({
  name: {
    type: String
  },
  email: {
    lowercase: true,
    type: String,
    trim: true,
    unique: true
  },
  password: {
    type: String,
  },
  postList: [{
    ref: 'posts',
    type: Schema.Types.ObjectId
  }],
});

const UserModel = mongoose.model('users', UserSchema);
module.exports = UserModel;

// save post controller
exports.savePost = (request, response, next) => {
  let { author, description, title } = request.body;
  let post = new PostModel({ author, description, title }).save();
  UserModel.findById(author)
    .then((user) => {
      user.postList.push(post);
      // Still Fails
      // How can i assign the post to the user ?
  });
}




有没有其他方法可以执行此操作,然后推送或填充?

3 个答案:

答案 0 :(得分:0)

要解决此问题,我更喜欢使用mongo的 $ push

ITunes account creation not allowed. This Apple ID cannot be used with the ITunes Store at this time. Please try again later.

答案 1 :(得分:0)

您需要按照此流程成功保存

  
      
  1. 如果成功则保存帖子
  2.   
  3. 更新用户以在postlist中推送postId
  4.   

可以尝试这个

exports.savePost = (request, response, next) => {
  let post = new PostModel(request.body)

  post.save(function(err, data) {
    if(err) {
       //return error
    }
    // check by console your author is present or not
    // let author in your req.body
    let author = req.body.author
    UserModel.findOneAndUpdate({_id: author},{$push: {postList: post._id}},{new:true} function(error, user) {
        if(error) {
          // return error
        }
        console.log(user)
        // return success
    })
  });
}

答案 2 :(得分:0)

exports.savePost = (request, response, next) => {
  let { user, description, title } = request.body;

  let post = new PostModel({ user, description, title });

  post.save()
    .catch((error) => {
      if (error) 
        throw new Error(error);
    })
    .then((post) => {
      UserModel.findOneAndUpdate({ _id: user }, {$push: { postList: post._id } })
      .populate('postList')
      .catch((error) => {
        if (error) 
          throw new Error(error);
      })
      .then((user) => {
        user.postList.forEach((item, postion) => {
          console.log(`${item} -at ${postion} \n`);
        });
      });

  });

}

这就是我所做的,毕竟它起作用了。我不知道这是否是正确的解决方案,但这是有效的。