Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

node.js - Nested arrays in Mongoose

In the collection I'm working on, a document looks like this:

{
    name: 'Myname',
    other: 'other',
    stuff: [
        ['something', 12, 4, 'somethingelse'],
        ['morestuff', 2, 4, 8],
        ['finally', 12, 'again', 58],

    ]
}

I wrote this Mongoose schema to access it:

var MyDocSchema = new Schema({
    name: String,
    other: String,
    stuff: [],
});

When I query a doc, everything works well, the output shown in the console is right. But when, I try to do console.log(myDoc.stuff), I got the following:

['something', 12, 4, 'somethingelse', 'morestuff', 2, 4, 8, 'finally', 12, 'again', 58]

instead of

[
    ['something', 12, 4, 'somethingelse'],
    ['morestuff', 2, 4, 8],
    ['finally', 12, 'again', 58],

]

What am I doing wrong? Thank you for your help!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Disclaimer: This response is pretty dated, 2012! It might not be the most accurate.

From the Mongoose documentation.

http://mongoosejs.com/docs/schematypes.html: Scroll down to the Array section:

Note: specifying an empty array is equivalent to [Mixed]. The following all create arrays of Mixed.

Details on what that means is in the Mixed section right above the Array section.

Here's what you need to do.

Define a schema for the embedded documents:

var Stuff = new Schema({
  name: String,
  value1: Number,
  ...
});

Use that instead of an empty array []:

var MyDocSchema = new Schema({
  name: String,
  other: String,
  stuff: [Stuff],
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...