Mongoose通过_idfind一个embedded式文档

我正尝试将菜单推送到embedded式文档。 但是我在餐厅没有定义findOne。 我只是想将一些文件推入餐厅的菜单类别。 正如您在架构中所见:

var RestaurantSchema = new mongoose.Schema({ contactTelphone : String, address : String, branchID : String, email : String, restaurantName : String, userID : String, menuCategory : [MenuCategorySchema] }); var MenuCategorySchema = new mongoose.Schema({ menuCategory : String, menuCategoryAlt : String, sequence : Number, menus : [MenuSchema], restaurantInfo : { type: Schema.Types.ObjectId, ref: 'Restaurant' }, }); var MenuSchema = new mongoose.Schema({ foodName : String, foodNameAlt : String, picName : String, price : String, rating : Number, menuSequence : Number, category : { type: Schema.Types.ObjectId, ref: 'MenuCategory' }, }); exports.menuForMenuCategory = function(newData, callback) { console.log(newData); var menuCategoryId = newData.menuCategoryId; var restaurantId = newData.restaurantId; var newMenu = new Menu({ foodName : newData.foodName, foodNameAlt : newData.foodNameAlt, picName : newData.picName, price : newData.price, cookingCategory : newCookingCategory, dishSpecial : newDishSpeical }); Restaurant.findOne( {'_id' : restaurantId }, function(err, restaurant){ if (!err) { //Is it how to do this? It says "findOne not defined" restaurant.findOne( "_id" : menuCategoryId, function(err, category){ category.push(newMenu); }); } }); } 

子文档有一个.id()方法,所以你可以这样做:

 myModel.findById(myDocumentId, function (err, myDocument) { var subDocument = myDocument.mySubdocuments.id(mySubDocumentId); }); 

请参阅http://mongoosejs.com/docs/subdocs.html以供参考。

restaurant只是一个包含查询结果的对象。 它没有一个findOne方法,只有Restaurant

因为, MenuCategory只是Restaurant一个子文档,所以无论何时你检索一个餐馆,都会预先填充。 例如

 Restaurant.findById(restaurantId, function(err, restaurant){ console.log(restaurant.menuCategory); // Will show your array of Menu Categories // No further queries required }); 

添加一个新的菜单类别是将一个新的MenuCategory实例推送到menuCategory数组并保存餐厅。 这意味着新的菜单类别与餐厅一起保存,而不是在单独的集合中。 例如:

 Restaurant.findById(restaurantId, function(err, restaurant){ // I'm assuming your Menu Category model is just MenuCategory var anotherMenuCategory = new MenuCategory({ menuCategory: "The name", menuCategoryAlt: "Alternative name", sequence: 42, menus: [] }); restaurant.menuCategory.push(anotherMenuCategory); restaurant.save(); // This will save the new Menu Category in your restaurant }); 

将菜单保存到菜单类别遵循相同的过程,因为根据您的模式,菜单是每个MenuCategory中embedded的子文档。 但请注意,您需要将餐厅保存为其所有菜单和菜单类别作为子文档的餐厅集合

回答你的问题(我希望),我也应该指出你的模式devise应该重新考虑。 有子文件嵌套在子文件中可以说是不是一个好主意。 我想我可以看到你来自哪里 – 你试图在模式中实现一个类似于SQL的多对一关联。 但是在NoSQL数据库中这不是必须的 – 思路有所不同。 下面是一些关于如何使用NoSQL数据库进行高效的模式devise的问题的链接:

  • MongoDB架构devise – 许多小文件或更less的大文件?
  • 我应该如何在MongoDB中实现这个模式?
  • MongoDB的关系:embedded或引用?