简体   繁体   English

更新 Mongoose 中数组中的子文档

[英]Updating a subdocument in array in Mongoose

I have two models, defined in two seperate files我有两个模型,在两个单独的文件中定义

//models/Projects.js
const mongoose = require('mongoose');

export const projectSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
    },
    companyBackground: {
        type: String,
        required: false,
        trim: true,
    }
});
module.exports = mongoose.models.Project || mongoose.model('Project', projectSchema);
//models/User.js
const mongoose = require('mongoose');
const { projectSchema } = require('./Project');

const userSchema = new mongoose.Schema({
    projects: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Project' }]
});

module.exports = mongoose.models.User || mongoose.model('User', userSchema);

I create a new user, and then create a new project, by pushing it to the user我创建一个新用户,然后通过将其推送给用户来创建一个新项目

import dbConnect from "utils/dbConnect";
import User from "models/User";
import Project from "models/Project";

export default async (req, res) => {
    await dbConnect();
    const { query: { id }, method } = req;

    switch (method) {
        case "POST":
            try {
                    const user = await User.findById(id);

                    if (!user) {
                        return res.status(400).json({ success: false, message: "User not found" });
                    }

                    const newProject = new Project(req.body);
                    console.log(newProject);
                    user.projects.push(newProject);
                    await user.save();

                    if (!user) {
                        return res.status(400).json({ success: false, message: "Project not added" 
                    }
                    res.status(200).json({ data: user });

            } catch (error) {
                res.status(400).json({ success: false, message: error.message });
            }
            break;
        default:
            res.status(400).json({ success: false });
            break;
    }
};

Bu here is the question.布这里是问题。 I can easily create a new project and save it to the user, but not make any updates.我可以轻松地创建一个新项目并将其保存给用户,但不进行任何更新。 Approaches I have tried include (but are not limited to):我尝试过的方法包括(但不限于):

To demonstrate the problems, see要演示这些问题,请参阅

const updateString = "projects.$." + req.body.property;
    Project.findOneAndUpdate(
        { _id: req.body.projectid },
            { $set: { [updateString]: req.body.value } },
                function (error, success) {
                    if (error) {
                        console.log('error');
                        console.log(error);
                    } else {
                        console.log("success");
                        console.log(success);  //Returns null
                    }
                }
    );

The above returns null以上返回 null

And when I do this, I get当我这样做时,我得到

User.findById(userid)
    .then((user => {
        const project = user.projects.id(req.body.projectid); //user.projects.id is not a function
        project.set(newContent);
        return user.save();
        }))
        .then((user) => {
            res.send(user);
        })
            .catch((error) => {
                console.log('error: ', error.message);
                res.status(400).json({ success: false, message: error.message });
    });

Here is says that user.projects.id is not a function... In mongo DB Atlas, I can see that the project has indeed been created.这里说 user.projects.id 不是 function... 在 mongo DB Atlas 中,我可以看到该项目确实已创建。

This is turning me crazy, can someone tell me what I am doing wrong?这让我发疯,有人能告诉我我做错了什么吗? Would it be better, simply to create the projects as arrays (without making them as a mongoose object?)只是将项目创建为 arrays 会更好吗(而不是将它们创建为 mongoose object?)

When pushing to user.projects you should just add the _id since the property is defined as ObjectId[] :推送到user.projects时,您应该只添加_id ,因为该属性定义为ObjectId[]

try {
  const user = await User.findById(id);

  if (!user) {
    return res.status(400).json({ success: false, message: 'User not found' });
  }

  const newProject = await Project.create(req.body);
  console.log(newProject);
  user.projects.push(newProject._id);
  await user.save();

  if (!user) {
    return res
      .status(400)
      .json({ success: false, message: 'Project not added' });
  }
  res.status(200).json({ data: user });
} catch (error) {
  res.status(400).json({ success: false, message: error.message });
}

Then, to update a Project you can simply do:然后,要更新Project ,您只需执行以下操作:

    Project.findByIdAndUpdate(
        req.body.projectid,
        { $set: { [req.body.property]: req.body.value } },
        { new: true }, // returns updated doc
        function (error, success) {
            if (error) {
                console.log('error');
                console.log(error);
            } else {
                console.log("success");
                console.log(success);  //Returns null
            }
        }
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM