获取集合中的所有项目

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

假设我有这样的东西:

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

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

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

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

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

而且,如果你想一次创build多个文档,你应该把一个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 } ]