[英]Mongoose array won't sort
mongodb文檔包含一個數組。 當使用貓鼬和graphql檢索到前端時,在數組上使用.sort()會引發錯誤。
無法分配為只讀對象“ [對象數組]”的屬性“ 1”
但是,在完全相同的數組上使用.sort()(這次是硬編碼)是可行的。
這里發生了什么事?!
const c = [ { slug: 'first-element',
position: 1,
alphaPos: 'B',
type: 'heading',
data: 'first-el B' },
{ slug: 'second-element',
position: 2,
alphaPos: 'C',
type: 'textarea',
data: 'second-el C' },
{ slug: 'third-element',
position: 3,
alphaPos: 'A',
type: 'textarea',
data: 'third-el A' },
{ slug: 'third-b-element',
position: 3,
alphaPos: 'D',
type: 'textarea',
data: 'third-el-22222 D' } ]
// 'content' is the same as 'c' but it comes from mongoose,
// it throws an error
console.log('content ==', content.sort())
// 'c' is hard coded, no error is thrown
console.log('content ==', c.sort())
// console.log(c) and console.log(content) output exactly the same array
[編輯:這是mongo文件]
{
"_id" : ObjectId("5a801422f1c5437466c5d285"),
"createdAt" : ISODate("2018-02-11T10:00:02.800Z"),
"id" : 1,
"slug" : "interesting-story",
"creatorId" : 3,
"title" : "An interesting story",
"image" : "/images/image1.jpg",
"description" : "description",
"content" : [
{
"slug" : "first-element",
"position" : 1,
"alphaPos" : "B",
"type" : "heading",
"data" : "first-el B"
},
{
"slug" : "second-element",
"position" : 2,
"alphaPos" : "C",
"type" : "textarea",
"data" : "second-el C"
},
{
"slug" : "third-element",
"position" : 3,
"alphaPos" : "A",
"type" : "textarea",
"data" : "third-el A"
},
{
"slug" : "third-b-element",
"position" : 3,
"alphaPos" : "D",
"type" : "textarea",
"data" : "third-el-22222 D"
}
],
"__v" : 0
}
這是架構
const postSchema = new Schema({
id: { type: Number, required: true, unique: true },
slug: { type: String, required: true, unique: true },
creatorId: { type: Number, required: true },
title: { type: String, required: true },
image: { type: String, required: false },
description: { type: String, required: true },
content: { type: Array, required: false },
createdAt: { type: Date, default: Date.now },
})
因為這些是2種不同的排序,所以取決於您所說的排序。 如果在數組(“硬編碼”)上調用它,它將使用默認的排序功能https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort,並且如果不能在mongodocument對象類型,無需編寫排序功能。
要使用貓鼬排序,必須在構建查詢時應用它
collection.find().sort().then(...)
萬一有人遇到相同的錯誤,我仍然無法解釋,但數組被視為對象,其中索引是鍵...
如果有人對此行為有一個解釋,我會很感興趣(與graphql?有關的是貓鼬嗎?也許與graphql-type-json包有關?)。
因此,要進行排序,這就是我正在做的事情(輸出一個數組)。
Object.keys(content).sort(a=>1).reduce((_sortedObj, key) => {
_sortedObj.push(content[key])
return _sortedObj
}, [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.