【问题标题】:Mongoose assign a collection to anotherMongoose 将一个集合分配给另一个
【发布时间】:2017-01-09 01:53:09
【问题描述】:

在使用空帖子创建用户后,我试图将帖子添加到用户集合中。我尝试过填充但没有成功.. 非常感谢任何帮助。

// 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 ?
  });
}

除了推送或填充之外,还有其他方法吗?

【问题讨论】:

  • 你遇到了什么问题?
  • @ShaishabRoy 真的什么也做不了。它始终为空

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


【解决方案1】:

为了解决这个问题我更喜欢使用 $push 的 mongo

UserModel.findOneAndUpdate({
    _id: author.id,
   {
        $push: {
                postList: post
            }
        }

});

【讨论】:

  • exec() 是为了执行查询而必须做的事情吗? findOneAndUpdate() 返回一个正确的承诺,所以你可以 .then() 方法。我是不是误会了什么?
  • 不,你是对的。这是旧代码。对不起。我只是修改帖子。
【解决方案2】:

你需要按照这个过程保存成功

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

可以试试这个

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
    })
  });
}

【讨论】:

  • 最终我得到了一个包含所有 id 的数组,但我想从帖子中获取所有信息,如帖子标题、帖子描述等。这个解决方案是否适用? @Shaishab 罗伊
  • 要获取用户的所有帖子信息,您应该创建另一个函数,该函数将使用 populate @DragosPodaru 返回用户的所有帖子信息。
【解决方案3】:

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`);
        });
      });

  });

}

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

【讨论】:

    猜你喜欢
    • 2015-11-26
    • 2021-07-10
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多