简体   繁体   English

Mongodb文档中如何将数组的元素复制到数组中

[英]How to copy the elements of an array into an array in a Mongodb document

I have an array我有一个数组

 let data = [a, b, c, d, e];

And I want to insert the elements of this array into an array in a MongoDb document.我想将这个数组的元素插入到 MongoDb 文档中的一个数组中。 This is my schema.这是我的架构。

 const userSchema = mongoose.Schema({
     info: reqString,
     data: [String]
 });

As you can see the data field represents an array.如您所见,数据字段代表一个数组。 In my index.js I use a for-loop to iterate through the array.在我的 index.js 中,我使用 for 循环遍历数组。

 for(var i= 0; i < data.length; i++){
     connectToDb(data[i]);
 }

And the connectToDb() is here: connectToDb() 在这里:

const connectToMongoDB = async (_data) => {
     await mongo().then(async (mongoose) => {
     try {
             console.log('Connected to mongodb!');

             await userSchema.findOneAndUpdate({
                 info: 'facts',
             }, {
                    $push: {
                         data: _data,
                    }
             });
         } finally {
             mongoose.connection.close();
             console.log('Disconnected from mongodb!');
         }
     });
 }

However although a documents is created in MongoDb, the data field which represents the array remains empty.但是,尽管在 MongoDb 中创建了文档,但表示数组的数据字段仍然为空。 I welcome all suggestions我欢迎所有建议

From your question it is not clear if you want to set the data field value with your _data array, or append your _data array to the existing array in the data field.从你的问题中不清楚你是否想用你的 _data 数组设置data字段值,或者_data你的_data数组到data字段中的现有数组。

1. To replace the array of the data field: 1.替换data字段的数组:

        await userSchema.findOneAndUpdate(
            { info: 'facts' },
            { $set: { data: _data } }
        ).exec();

2. To append an array to the array of the data field: 2.把append一个数组给data字段的数组:

        await userSchema.findOneAndUpdate(
            { info: 'facts' },
            { $push: { data: { $each: _data } } }
        ).exec();

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

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