我正在创建一个网站。在我的服务器内部有一个 mongoose 模型,它在 mongo 数据库中保存不同的数据,例如出生日期。以 ISODate 格式存储的日期。但我只想在客户端内的反应组件中使用年份或月份。我怎样才能做到这一点? 有什么方法可以在从 mongodb 调用的 React 组件中格式化日期吗?
import mongoose from 'mongoose';
const listingSchema = new mongoose.Schema(
{
givenname: {
type: String,
required: true,
},
familyname: {
type: String,
required: true,
},
dateofbirth: {
type: Date,
required: true,
},
dateofpassing: {
type: Date,
required: true,
},
imageUrl: {
type: String,
default: "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"
},
userRef: {
type: String,
required: true,
},
}, {timestamps: true}
)
const Listing = mongoose.model('Listing', listingSchema);
export default Listing;
import { useSelector } from 'react-redux';
import { useRef, useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';
export default function () {
const { currentUser, loading, error } = useSelector((state) => state.user);
const [showListingsError, setShowListingsError] = useState(false);
const [userListings, setUserListings] = useState([]);
const dispatch = useDispatch();
const handleShowListings = async () => {
try {
setShowListingsError(false);
const res = await fetch(`/api/user/listings/${currentUser._id}`);
const data = await res.json();
if (data.success === false) {
setShowListingsError(true);
return;
}
setUserListings(data);
} catch (error) {
setShowListingsError(true);
}
};
return (
<div>
<button onClick={handleShowListings}>Show Memorials</button>
{userListings && userListings.length > 0 && userListings.map((listing)=>
<div key={listing._id}>
<Link>
<div>
<img src={listing.imageUrl} alt="Person image" />
<div>
<h1>{listing.givenname + ' ' + listing.familyname}</h1>
<p>{listing.dateofbirth.year + '-' + listing.dateofpassing.year}</p>
</div>
</div>
</Link>
</div>)}
</div>
)
}
您可以更新架构以包含虚拟。
这会将计算属性添加到您的文档中,您可以在 React 前端使用这些属性。这些不会显示在 mongodb 中,因此您无法查询它们,只能使用 mongoose 输出。
注意我已经为您添加了
toJSON: { virtuals: true }
选项,因为否则当您将文档转换为 JSON 以通过网络发送时,默认情况下虚拟值不是 JSON 对象的一部分。
const listingSchema = new mongoose.Schema(
{
//...
dateofbirth: {
type: Date,
required: true,
},
//...
//..
},
{
timestamps: true,
toJSON: {
virtuals: true
},
virtuals: {
yearOfBirth: {
get() {
const nd = new Date(this.dateofbirth);
return nd.getFullYear();
},
},
monthOfBirthDigit: {
get() {
const nd = new Date(this.dateofbirth);
return nd.getMonth();
},
},
monthOfBirthShortWord: {
get() {
const nd = new Date(this.dateofbirth);
return nd.toLocaleString('default', { month: 'short' });
},
}
}
}
)
然后当你查询它们时:
const document = await Listing.findById(id);
console.log(document.yearOfBirth);
// 1980
console.log(document.monthOfBirthDigit);
// 10
console.log(document.monthOfBirthShortWord);
// Oct