简体   繁体   English

在 Javascript 上使用 Mongoose 将对象数组保存到 MongoDB

[英]save an array of objects to MongoDB with Mongoose on Javascript

I have this data (json):我有这个数据(json):

 var unique = [ {"name":"John", "number":"4132321234"}, {"name":"Jack", "number":"451232421234"}, {"name":"Maddy", "number":"12314124"}, {"name":"Alex", "number":"213468316"} ]

What I want to do, is save this data to my mongoDB collection, with the following schema (using mongoose):我想要做的是将此数据保存到我的 mongoDB 集合中,使用以下模式(使用猫鼬):

 const mongoose = require('mongoose') const Schema = mongoose.Schema const nameSchema = new Schema({ name: { type: String, required: true, }, number: { type: String, required: true, }, }); const Name_db = mongoose.model('Name_db', nameSchema) module.exports = Name_db;

I wrote a loop, to attempt to do this:我写了一个循环,试图做到这一点:

 for (var k = 1; k < unique.length; k++) { var name_mongo = new Name_db({ name: unique[k].name, number: unique[k].number, }, ) console.log(unique[k].name) } name_mongo.save().then(results => { res.send(results) }).catch(err => { console.log(err);})

This doesn't work because right now it is only sending data once to mongo DB, meaning only of the arrays is actually being sent over, instead of all 3 of them being sent to mongoDB.这不起作用,因为现在它只向 mongo DB 发送一次数据,这意味着实际上只有 arrays 被发送过来,而不是全部 3 个被发送到 mongoDB。

Would appreciate any help, thank you for the time.将不胜感激任何帮助,谢谢你的时间。

Name_db.insertMany(unique)
    .then((result) => console.log("Inserted", result))
    .catch((error) console.log(error));

or或者

const result = await Name_db.insertMany(unique); // remember to decorate the function async

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

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