简体   繁体   English

使用Mongoose将嵌套集合插入Mongodb

[英]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. 我正在尝试使用Node.JS和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. 上面的代码无论如何都不会填充“ ref”字段。

As the comment above by @WiredPrairie shows, ref should be an array, not an object like you have it defined in your schema. 正如@WiredPrairie上面的注释所示, ref应该是一个数组,而不是像在架构中定义的对象。 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. 但是,由于ref是URL(字符串)的简单集合,因此每个ref都不需要url属性,因此不必是一个对象。

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 . 另外,您可能会发现将keyw为数组会更适合您,因为使用$ in运算符可以更轻松地基于关键字查找文档。

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 . 由于这是一个文档,因此不需要$addToSet Use that operator when updating . 更新时使用该运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM