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

编程入门 行业动态 更新时间:2024-10-12 14:20:01

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用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

更多推荐

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

本文发布于:2024-05-07 06:41:13,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   文档   Mongoose   Express   Node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!