mongoose.insertMany中数组对象的格式错误

时间:2017-10-10 02:50:47

标签: javascript mongoose

根据mongoose doc,它声明参数doc(s)是

我试图插入arrobj(见下文),但失败并出现错误。但是当我用records2模拟它时,它设法插入。最初,它认为它是引号或数组,我将其更改为字符串。它仍然无法正常工作。然后我使用JSON.parse,它也不起作用。使用insertMany的正确方法是什么?还是更好的选择?

const mongoose = require('mongoose');
const db = require('./model/db1');
let arrobj = [
    ["T1", "T2", "T3", "T4", "T5"],
    ["A1", "A2", "A3", "A4", "A5"],
    ["R1", "R2", "R3", "R4", "R5"],
    ["D1", "D2", "D3", "D4", "D5"],
    ["r1", "r2", "r3", "r4", "r5"]
];

(async () => {
    const aModel = mongoose.model('aModel'); // retrieve the model
    await insertDocuments(aModel, arrobj);
    done();
})();

function done(err) {
    if (err) console.error(err.stack);
    mongoose.connection.close();
}

async function insertDocuments(model, arrobj) {
    let records = await remap(arrobj);
    // This simulated record has no error.
    /* let records2 = [ {title : 'T1', author : 'A1', review : 'R1', date : 'D1',      rating : 'R1'},  {title : 'T2', author : 'A2', review : 'R2', date : 'D2', rating : 'R2'}];
     */
    try {
        await model.insertMany(records);
    } catch (err) {
        console.log('ERR:', err.message);
    }
    //console.log(results)
    //return IDs;
}

async function remap(arrobj) {
    let str = '',
        record = '';
    let doc = [];
    for (let j = 0; j < arrobj.length - 1; j++) {
        record = '{title : "' + arrobj[0][j] + '", author: "' + arrobj[1][j] + '", review: "' + arrobj[2][j] + `", date: "` + arrobj[3][j] + '", rating: "' + arrobj[4][j] + '"}';
        //records.push(record);
        str = str.concat(record, ',');
    }
    record = '{title : "' + arrobj[0][arrobj.length - 1] + '", author: "' + arrobj[1][arrobj.length - 1] + '", review: "' + arrobj[2][arrobj.length - 1] + `", date: "` + arrobj[3][arrobj.length - 1] + '", rating: "' + arrobj[4][arrobj.length - 1] + '"}';
    doc = str.concat(record);
    doc = '[{title : "' + arrobj[0][0] + '", author: "' + arrobj[1][0] + '",  review: "' + arrobj[2][0] + `", date: "` + arrobj[3][0] + '", rating: "' + arrobj[4][0] + '"}]';
    return doc;
}

1 个答案:

答案 0 :(得分:0)

试试这个:

function remap(arrobj) {
  let records = []

  for (let j = 0; j < arrobj.length - 1; j++) {

    let record = {
      title:  arrobj[0][j],
      author: arrobj[1][j],
      review: arrobj[2][j],
      date:   arrobj[3][j],
      rating: arrobj[4][j]
    }

    records.push(record)
  }

  return records
}