gpt4 book ai didi

javascript - Mongoose 从集合中获取所有键值并将其放入数组中

转载 作者:行者123 更新时间:2023-12-01 00:24:07 25 4
gpt4 key购买 nike

如何将名为“用户名”和“用户名”以及“密码”(密码哈希)的所有键提取到两个单独的数组中?到目前为止我尝试过的:

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);
});
});

关于javascript - Mongoose 从集合中获取所有键值并将其放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59157526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com