I'm trying to populate a db with some default dummy data in order to speed up testing. This is part of a project that uses https://github.com/angular-fullstack/generator-angular-fullstack and I'm attempting to use promises for the first time.
Assuming I have something like:
Thing.create({
name: 'thing 1'
}, {
name: 'thing 2'
}).then((things) => {
console.log(things);
});
Why does the console log only output thing 1
and not the whole collection?
According to the mongoose docs http://mongoosejs.com/docs/api.html#model_Model.create, the method returns a promise which doesn't seem to help me.
In order for Mongoose to return a Promise
you need to set this accordingly in your Mongoose instance:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
Furthermore, if you want to create multiple documents at once, you should pass an array
to the .create
method:
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 } ]