Noob问题,但是如何在不声明新const的情况下创建具有相同架构的多个文档。我是否需要为每个键创建一个数组,例如
const newItem = new Item({
name: ["Blue Shirt", "Green Shirt"],
image: ["images/image-1.jpg","images/image-2.jpg"],
price: [30, 20],
quantity: [5, 10]
});
<------------原码------------->
const newItem = new Item({
name: "Blue Shirt",
image: "https://picsum.photos/id/237/200/300",
price: 30,
quantity: 5
});
答案 0 :(得分:1)
您必须创建一个数据数组。
const newItem = new Item({
name: "Blue Shirt",
image: "https://picsum.photos/id/237/200/300",
price: 30,
quantity: 5
});
var arr = [newItem]; //Pass array of documents / objects.
Item.insertMany(arr, function(error, docs) {});
或
var arr = ['{
name: "Blue Shirt",
image: "https://picsum.photos/id/237/200/300",
price: 30,
quantity: 5
}', {
name: "Blue Shirt",
image: "https://picsum.photos/id/237/200/300",
price: 30,
quantity: 5
}]; //Pass array of documents / objects.
Item.insertMany(arr, function(error, docs) {});
您可以在https://mongoosejs.com/docs/api.html#model_Model.insertMany
上探索更多内容