我如何更改字段名称作为函数参数mongoDB [英] How can i change the name of a field as a function argument mongoDB

查看:192
本文介绍了我如何更改字段名称作为函数参数mongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mongoDB,我想拥有以下架构:

I have a mongoDB and i want to have the following schema :

directory: {
    "file1": "id",
    "directory1":{
        "file1": "..."
        "file2": "..."
        "file3": "..."
        "direcrtory1": {}
   } 
}

我的问题是:如何选择函数$ push的字段名称作为以下函数的参数?

My question is: how can i select the field name of function $push as an argument for the following function?

function createFile(projectId,filename,id){
        return Project.updateOne({projectId:projectId},{$push:{directory:{filename: id}}});
}

上面的代码在数据库中创建此代码:

The code above creates this in the database:

"directory": [
    {
        "id": "someID",
        "filename": "something"
    }

现在,我不希望以这种方式命名文件名".我希望它被命名为通过函数传递的值

Now, I don't want the 'filename' be named that way. I want it to be named as the value that was transferred through the function

示例:如果函数获取以下参数(someID,'something','anotherId ),在数据库中,我将拥有'filename':'anotherId',而我想要的输出是:'something':'anotherId'.我该怎么办?

example: if function gets the following parameters(someID,'something','anotherId ) , in the database i will have 'filename':'anotherId', and the output i want to have is : 'something':'anotherId' . How can I get that?

任何帮助将不胜感激

解决方案:

var update = {$set:{}};
update.$set[filename] = id;
Project.updateOne({projectId: projectId},update,{upsert: true});

推荐答案

使用Mongoose模式的要点是强制Mongo集合中对象的形状.它不会保留不符合架构的字段.如果您希望每个存储的对象都具有与您描述的不同的字段,则需要直接使用MongoClient来保存一个普通的JS对象,或者在您希望其变量名出现的模式中定义一个Mixed类型.

The point of using a Mongoose Schema is to enforce the shape of the objects in a Mongo collection. It won't persist fields that don't conform to the schema. If you want each stored object to have different fields like you're describing, you need to either use the MongoClient directly to save a plain JS object, or else define a Mixed type in your schema where you want the variable names to occur.

如果要进行后者,请注意,保存之前必须先调用markModified()才能使Mongoose识别发生的更改.

If you do the latter,note that you have to call markModified() before saving to get Mongoose to recognize the change occurred.

好,所以为猫鼬添加一个示例.你只要照我说的做就行.

Ok, so adding an example for Mongoose. You'd just do what I said.

  const DirectorySchema = new Schema({ 
             path: String,
             contents: Mixed 
   });

然后,目录"字段可以存储您想要的任何内容,但是您必须在保存基于该架构的模型之前调用markModified.

Then the "contents" field can store whatever you want, but you have to call markModified before saving a model based on that schema.

这篇关于我如何更改字段名称作为函数参数mongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆