如何使用 NodeJS 仅将 NeDB 数据库中的某些字段存储到数组中
Posted
技术标签:
【中文标题】如何使用 NodeJS 仅将 NeDB 数据库中的某些字段存储到数组中【英文标题】:How to store only certain fields from NeDB database into an array with NodeJS 【发布时间】:2021-07-31 09:47:41 【问题描述】:我有一个嵌入式 NeDB 数据库,其中包含多个具有多个字段的条目,我希望只从每个条目中获取日期并将其存储到一个数组中。我正在使用 NeDB、NodeJS 和 express。
数据集如下所示:
"goalName":"swim 5km","details":"I want to swim 5km","date":"2021-05-15","completed":false,"author":"somename","_id":"BMnvTm54rNbwc9D4"
"goalName":"swim 5km","details":" I want to swim another 5km","date":"2021-03-14","completed":false,"author":"somename","_id":"EwEicEYZAfFxY9Z6"
"goalName":"20 pushups","details":"I want to complete 20 full pushups","date":"2021-05-14","completed":false,"author":"anthername","_id":"rP7q6L8jnwGyAgGD"
我只对作者姓名的日期感兴趣,
我可以使用以下方法检索这些文档:
getEntriesByUser(userName)
return new Promise((resolve, reject) =>
this.db.find( 'author': userName , function (err, entries)
if (err)
reject(err);
else
resolve(entries);
console.log('getEntriesByUser returns: ', entries);
)
)
然后返回用户名 = someusername 的文档,但我只对日期感兴趣。最好将它们存储到一个数组中,结果如下:
[2021-05-15, 2021-03-14, 2021-05-14]
我该怎么做呢?
感谢您的帮助!
【问题讨论】:
【参考方案1】:您可以使用find()
和findOne()
方法的可选第二个projection
参数来包含或省略返回记录的属性。见:NeDB#projections。
db.find( author: userName , date: 1, _id: 0 , function (err, docs) ...);
const
Datastore = Nedb,
db = new Datastore(),
data = [
goalName: "swim 5km", details: "I want to swim 5km", date: "2021-05-15", completed: false, author: "somename" ,
goalName: "swim 5km", details: " I want to swim another 5km", date: "2021-03-14", completed: false, author: "somename" ,
goalName: "20 pushups", details: "I want to complete 20 full pushups", date: "2021-05-14", completed: false, author: "anthername" ,
];
for (const datum of data)
db.insert(datum);
function getEntriesByUser(userName)
return new Promise((resolve, reject) =>
db.find( author: userName , date: 1, _id: 0 , function (err, entries)
if (err)
reject(err);
else
resolve(entries);
console.log('getEntriesByUser returns: ', entries);
)
)
getEntriesByUser('somename').then((entries) =>
console.log('Mapped return value: ', entries.map(( date ) => date));
);
.as-console-wrapper max-height: 100% !important; top: 0;
<script src="https://cdnjs.cloudflare.com/ajax/libs/nedb/1.8.0/nedb.min.js"></script>
【讨论】:
以上是关于如何使用 NodeJS 仅将 NeDB 数据库中的某些字段存储到数组中的主要内容,如果未能解决你的问题,请参考以下文章
NEDB & Nodejs:使用用户输入在 home.db 中搜索特定记录 - 无法将参数传递给 index.js