如何通过 mongoose 将多个数组元素推送到 mongodb
Posted
技术标签:
【中文标题】如何通过 mongoose 将多个数组元素推送到 mongodb【英文标题】:How To Push mutiple array elements into mongod by mongoose 【发布时间】:2020-08-02 20:14:14 【问题描述】:有一个包含这些字段的mongodb Schema,它的类型是数组
......
orderlist: [
id: String,
price: Number,
photo: String,
name: String,
num: Number
]
......
前端发给我这样的数据,这个数组有很多数组元素
goodslist:[
goodsid: '10001',
goodsprice: 20,
goodsphoto: '/goodsimg/upload_1843.jpg',
goodsname: 'goods1',
goodsnum: 2
,
goodsid: '10002',
goodsprice: 30,
goodsphoto: '/goodsimg/upload_1845.jpg',
goodsname: 'goods2',
goodsnum: 4
,
........(etc)
]
如何在不更改 mongodb 字段的情况下通过 mongoose 将这个 'goodslist' 数据推送到 'orderlist' 字段中,谢谢
【问题讨论】:
【参考方案1】:您必须使用mongoose virtuals 来解决此问题。
您的架构必须是这样的:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const collectionName = 'orderlist';
const OrderSchema = new Schema(
id: String,
price: Number,
photo: String,
name: String,
num: Number
, minimize: false );
const OrderlistSchema = new Schema(
orderList: [OrderSchema]
, minimize: false, toJSON: virtuals: true );
OrderlistSchema.virtual('goodslist').
get(function ()
return this.orderList.map(order => (
goodsid: order.id,
goodsprice: order.price,
goodsphoto: order.photo,
goodsname: order.name,
goodsnum: order.num
))
).
set(function (v)
this.set(
orderList: v.map(good => (
id: good.goodsid,
price: good.goodsprice,
photo: good.goodsphoto,
name: good.goodsname,
num: good.goodsnum
))
);
);
module.exports = mongoose.model('Orderlist', OrderlistSchema, collectionName);
goodslist
是这里的虚拟字段。
使用此模式,您可以使用您的格式设置订单字段,而无需更改 mongodb 中的任何内容。
过帐文件示例:
"goodslist": [
"goodsid": 2,
"goodsprice": 200,
"goodsphoto": "photo2",
"goodsname": "name2",
"goodsnum": 1234
]
还可以获取goodlist格式的订单数据
"_id": "5e9d8c0e27c7a813840c9ff0",
"orderList": [
"_id": "5e9d8c0e27c7a813840c9ff1",
"id": "2",
"price": 200,
"photo": "photo2",
"name": "name2",
"num": 1234
],
"__v": 0,
"goodslist": [
"goodsid": "2",
"goodsprice": 200,
"goodsphoto": "photo2",
"goodsname": "name2",
"goodsnum": 1234
],
"id": "5e9d8c0e27c7a813840c9ff0"
【讨论】:
【参考方案2】:它将类似于以下内容:
//Update order | create if does not exist
orderDB.updateOne( _id: 'xxxx' ,
//Push the list into order array
$push:
orderlist: [
id: goodlist[0][0],
price: goodlist[0][1],
photo: goodlist[0][2],
name: goodlist[0][3],
num: goodlist[0][4],
]
//Upsert => update / create
, upsert: true )
但是,您可能需要遍历商品列表。
【讨论】:
以上是关于如何通过 mongoose 将多个数组元素推送到 mongodb的主要内容,如果未能解决你的问题,请参考以下文章