最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用Mongoose,Express和Node更新MongoDB中的子文档?

网站源码admin16浏览0评论

如何使用Mongoose,Express和Node更新MongoDB中的子文档?

如何使用Mongoose,Express和Node更新MongoDB中的子文档?

所以我有一个Mongoose名为Profile的模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const ProfileSchema = new Schema({
  user: {
    type: mongoose.Schema.ObjectId,
    ref: "user",
  },
  company: {
    type: String,
  },
  website: {
    type: String,
  },
  location: {
    type: String,
  },
  status: {
    type: String,
    required: true,
  },
  skills: {
    type: [String],
    required: true,
  },
  bio: {
    type: String,
  },
  githubusername: {
    type: String,
  },
  experience: [{
    title: {
      type: String,
      required: true,
    },
    company: {
      type: String,
      required: true,
    },
    location: {
      type: String,
    },
    from: {
      type: Date,
      required: true,
    },
    to: {
      type: Date,
    },
    current: {
      type: Boolean,
      default: false,
    },
    description: {
      type: String,
    },
  }, ],
  education: [{
    school: {
      type: String,
      required: true,
    },
    degree: {
      type: String,
      required: true,
    },
    fieldofstudy: {
      type: String,
      required: true,
    },
    from: {
      type: Date,
      required: true,
    },
    to: {
      type: Date,
    },
    current: {
      type: Boolean,
      default: false,
    },
    description: {
      type: String,
    },
  }, ],
  social: {
    youtube: {
      type: String,
    },
    twitter: {
      type: String,
    },
    facebook: {
      type: String,
    },
    linkedin: {
      type: String,
    },
    instagram: {
      type: String,
    },
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = Profile = mongoose.model("profile", ProfileSchema);
回答如下:

无法将猫鼬模型架构作为Profile对象访问。相反,如果要更新模型的特定部分(在这种情况下为experience),则可以执行以下操作:

Profile.findByIdAndUpdate(
    { _id: req.params.exp_id}, 
    { $set: { experience: req.body} }, 
    { new: true }, your_callback);

我也相信是req.params.exp_id而不是req.params._id

发布评论

评论列表(0)

  1. 暂无评论