如何将带有“密码”(密码哈希)的名为“用户名”和“用户名”的所有键提取到两个单独的数组中? 到目前为止,我已经尝试过:
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"
}
答案 0 :(得分:2)
在结果中使用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);
});
});