简体   繁体   中英

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. 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.

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

And the connectToDb() is here:

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. 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.

1. To replace the array of the data field:

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

2. To append an array to the array of the data field:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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