获取集合中的所有项目
Get all items in collection
我正在尝试用一些默认的虚拟数据填充数据库以加快测试速度。这是使用 https://github.com/angular-fullstack/generator-angular-fullstack 的项目的一部分,我是第一次尝试使用 promises。
假设我有类似的东西:
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,方法 returns 似乎对我没有帮助。
为了让 Mongoose return 一个 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 } ]
我正在尝试用一些默认的虚拟数据填充数据库以加快测试速度。这是使用 https://github.com/angular-fullstack/generator-angular-fullstack 的项目的一部分,我是第一次尝试使用 promises。
假设我有类似的东西:
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,方法 returns 似乎对我没有帮助。
为了让 Mongoose return 一个 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 } ]