【问题标题】:Mongoose with mongodb how to return just saved object that have full or customize property with other collection?Mongoose 与 mongodb 如何返回刚刚保存的具有完整或自定义属性的对象与其他集合?
【发布时间】:2022-03-01 08:36:20
【问题描述】:

我需要你的帮助。我面临的问题是我无法获得从已保存返回的完整属性或自定义属性。我的解释如下:

后模型:

const postSchema = new mongoose.Schema(
  {
    content: {
      type: String,
      trim: true,
      required: [true, "Post must be required"],
    },
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    liked: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    ],
    disliked: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    ],
    imageUrl: {
      type: String,
      trim: true,
    },
  },
  { timestamps: true }
);

用户模型:

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        unique: true,
        trim: true,
        required: [true, 'Name must be required']
    },
    email: {
        type: String,
        unique: true,
        trim: true,
        required: [true, 'Email must be required']
    },
    password: {
        type: String,
        unique: true,
        trim: true,
        required: [true, 'Password must be required'],
        minlength: [6, 'Password must be at least 6 characters']
    },

}, {timestamps: true});

函数创建新的帖子并将帖子回复到客户端:

exports.createOnePost = async (req, res, next) => {
  console.log("create one");
  try {
    const post = await Post.create({
      content: req.body.content,
      author: req.user.userId,
      liked: req.body.liked,
      imageUrl: req.body.imgUrl,
    });
    res.status(200).json({
      status: "success",
      data: { post },
    });
  } catch (error) {
    next(error);
  }
};

将 Post 保存到数据库后,我还想返回 User 和 Post 的完整属性。 但我刚刚收到一个帖子:

{
  content: 'sfdfsfd44434',
  author: new ObjectId("61c1e08837d77c6187b9a746"),
  liked: [],
  disliked: [],
  _id: new ObjectId("620c77d7574ce70b2417c1a1"),
  createdAt: 2022-02-16T04:04:39.016Z,
  updatedAt: 2022-02-16T04:04:39.016Z,
  __v: 0
}

希望你们能提供解决方案。非常感谢!

【问题讨论】:

标签: node.js reactjs mongodb mongoose mongodb-query


【解决方案1】:

由于您已经拥有该用户,您可以像这样在响应中返回它:

res.status(200).json({
  status: "success",
  data: { post: { ...post.toObject(), author: req.user } },
});

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 2016-03-08
    • 2016-06-30
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    相关资源
    最近更新 更多