boz boz - 1 year ago 91
Node.js Question

Get all items in collection

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 and I'm attempting to use promises for the first time.

Assuming I have something like:

name: 'thing 1'
}, {
name: 'thing 2'
}).then((things) => {

Why does the console log only output
thing 1
and not the whole collection?

According to the mongoose docs, the method returns a promise which doesn't seem to help me.

Answer Source

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 => {

// Outputs
[ { name: 'Thing 1', _id: 57fd82973b4a85be9da73b25 },
  { name: 'Thing 2', _id: 57fd82973b4a85be9da73b26 },
  { name: 'Thing 3', _id: 57fd82973b4a85be9da73b27 } ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download