简体   繁体   English

更新嵌入的文档猫鼬

[英]Update embedded document mongoose

I'm looking for an easy way of updating an embedded document using mongoose without having to set each specific field manually.我正在寻找一种使用 mongoose 更新嵌入文档的简单方法,而无需手动设置每个特定字段。 Looking at the accepted answer to this question , once you find the embedded document that you want to update you have to actually set each respective property and then save the parent.查看此问题的已接受答案,一旦找到要更新的嵌入文档,您必须实际设置每个相应的属性,然后保存父级。 What I would prefer to do is pass in an update object and let MongoDB set the updates.我更愿意做的是传入一个更新对象并让 MongoDB 设置更新。

eg if I was updating a regular (non embedded) document I would do this:例如,如果我正在更新常规(非嵌入)文档,我会这样做:

models.User.findOneAndUpdate({_id: req.params.userId}, req.body.user, function(err, user) {
    err ? resp.status(500).send(err) : user ? resp.send(user) : resp.status(404).send();
});

Here I don't actually have to go through each property in req.body.user and set the changes.在这里,我实际上不必遍历 req.body.user 中的每个属性并设置更改。 I can't find a way of doing this kind of thing with sub documents as well ?我也找不到用子文档做这种事情的方法?

My Schema is as follows:我的架构如下:

var UserSchema = BaseUserSchema.extend({ 
    isActivated: { type: Boolean, required: true },
    files: [FileSchema]
});

var FileSchema = new mongoose.Schema(
    name: { type: String, required: true },
    size: { type: Number, required: true },
    type: { type: String, required: true },
});

And I'm trying to update a file based on user and file id.我正在尝试根据用户和文件 ID 更新文件。

Do I need to create a helper function to set the values, or is there a MongoDB way of doing this ?我是否需要创建一个辅助函数来设置值,或者是否有 MongoDB 的方法来做到这一点?

Many thanks.非常感谢。

Well presuming that you have something that has you "filedata" in a variable, and of course the user _id that you are updating, then you wan't the $set operator:好吧,假设你有一些东西在一个变量中包含你的“文件数据”,当然还有你正在更新的用户 _id,那么你不需要$set运算符:

var user = { /* The user information, at least the _id */
var filedata = { /* From somewhere with _id, name, size, type */ };

models.User.findOneAndUpdate(
    { "_id": user._id, "files._id": filedata._id },
    {
        "$set": {
            "name": filedata.name,
            "size": filedata.size,
            "type": filedata.type
        }
    },
    function(err,user) {
      // Whatever in here such a message, but the update is already done.
    }
);

Or really, just only $set the fields that you actually mean to "update" as long as you know which ones you mean.或者实际上,只要您知道您的意思,只需$set您实际要“更新”的字段即可。 So if you only need to change the "size" then just set that for example.因此,如果您只需要更改“大小”,那么只需进行设置即可。

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

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