猫鼬从集合中获取所有键值并放入数组中

Mongoose fetch all key values from a collection and put into an array

如何将所有名为 'username' 和 'username' 的键与 'password'(密码哈希)一起提取到两个单独的数组中? 到目前为止我尝试了什么:

const mongoose = require('mongoose');
const User = require('./models/user.js');
// doesn't work!
const users = User.find().byName('username');
console.log(users);

我的user.js:

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({

    loginId: String,
    firstname: String,
    lastname: String,
    eMail: String,
    password: String,
    active: Boolean

});
module.exports = mongoose.model("User", userSchema);

更新: 期望的输出: 用户数组:

['bert', 'joe', 'john']

有密码的用户数组:

[ 'bert', 'bertpassword', 'joe', 'joespassword', 'john', 'johnspassword']

P.S 是的,这是一个登录系统。


虚拟用户条目:

{
    _id: "5dc16a477bfe45097018a074",
    loginId: "1",
    firstname: "Test",
    lastname: "Testeroni",
    eMail: "test@testeroni.test",
    password: "test",
    active: "true"
}

在结果中使用 Lodash flatten

npm i lodash --save

然后

const mongoose = require("mongoose");
const _ = require("lodash");

const User = mongoose.model(
    "user",
    new mongoose.Schema({
        loginId: String,
        firstname: String,
        lastname: String,
        eMail: String,
        password: String,
        active: Boolean
      })
  );

const db = mongoose.connection;

mongoose.connect("mongodb://localhost:27017/dbName", {
  useNewUrlParser: true
});

db.once("open", () => {
  User.find({}, { firstname: 1, password: 1 }, function(err, users) {
    const flattenUsers = _(users)
      .map(({ firstname, password }) => [firstname, password])
      .flatten()
      .value();
    console.log(flattenUsers);
  });
});