user1941621
user1941621

Reputation: 45

Inserting a nested collection into Mongodb with Mongoose

I have an array I am attempting to insert into a collection type with Node.JS and Mongoose. DB Schema defined as such:

//LIBRARY
var LibrarySchema = new mongoose.Schema({
    name: {type:String, required: true},
    keyw: {type:String, required: true},
    data: {type:String, required: true},
    ref: {url: String}
},
 {collection: 'library'}
)

I have been able to successfully insert the array (which shows up as a comma-delimited list) but can't seem to master what I assume is something simple. I have read through various documentation and this SHOULD work:

// Dummy Data
var b.topic = "This is my name"
var b.keywords = "keyword1,keyword2,keyword3"
var data = "This is some data, just another string"
var arrRef = []
arrRef[0] = "http://www.website1.com"
arrRef[1] = "http://www.website2.com"
//Create Schema & Save
var lib = new db.Library({
    name: b.topic,
    keyw: b.keywords,
    data: b.data,
    ref: {$addToSet: {url: arrRef}}
})
lib.save(function(err,docs) {
    console.log("Error:" + err)
}

What I'm trying to have in the data is:

name: "This is my name"
keyw: "keyword1,keyword2,keyword3"
data: "This is some data, just another string"
ref:
      url: "http://www.website1.com"
      url: "http://www.website2.com"

Any ideas on what I'm doing wrong? The code above does not populate the "ref" field whatsoever.

Upvotes: 0

Views: 2185

Answers (1)

talentedmrjones
talentedmrjones

Reputation: 8151

As the comment above by @WiredPrairie shows, ref should be an array, not an object like you have it defined in your schema. However, since ref is a simply collection of urls (strings), each one does not need the url property, and therefore does not need to be an object.

Also, you might find that making keyw an array will work better for you, because it will be easier to find documents based on keywords using the $in operator.

Try this schema:

{
    name: {type:String, required: true},
    keyw: {type:Array, required: true},
    data: {type:String, required: true},
    ref: []
}

And this code

var lib = new db.Library({
    name: b.topic,
    keyw: b.keywords.split(','),
    data: b.data,
    ref: arrRef
})

Since this is a new document, you don't need $addToSet. Use that operator when updating.

Upvotes: 1

Related Questions