【发布时间】:2018-07-21 16:01:12
【问题描述】:
一个 mongodb 文档包含一个数组。当使用 mongoose 和 graphql 检索到前端时,对数组使用 .sort() 会引发错误。
无法分配给对象“[object Array]”的只读属性“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 },
})
【问题讨论】:
标签: arrays node.js mongodb sorting