繁体   English   中英

获取集合中的所有项目

[英]Get all items in collection

我试图用一些默认的虚拟数据填充一个数据库,以加快测试速度。 这是使用https://github.com/angular-fullstack/generator-angular-fullstack的项目的一部分,我第一次尝试使用 promise。

假设我有类似的东西:

Thing.create({
  name: 'thing 1'
}, {
  name: 'thing 2'
}).then((things) => {
  console.log(things);
});

为什么控制台日志只输出thing 1而不是整个集合?

根据猫鼬文档http://mongoosejs.com/docs/api.html#model_Model.create ,该方法返回一个似乎对我没有帮助的承诺。

为了让 Mongoose 返回一个Promise你需要在你的 Mongoose 实例中进行相应的设置:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

此外,如果您想一次创建多个文档,您应该将一个array传递给.create方法:

let things = [
  {
    "name": "Thing 1"
  },
  {
    "name": "Thing 2"
  },
  {
    "name": "Thing 3"
  }
];

Thing.create(things).then(newThings => {
  console.log(newThings);
});

// Outputs
[ { name: 'Thing 1', _id: 57fd82973b4a85be9da73b25 },
  { name: 'Thing 2', _id: 57fd82973b4a85be9da73b26 },
  { name: 'Thing 3', _id: 57fd82973b4a85be9da73b27 } ]

暂无
暂无

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

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