2014-02-19 26 views
0

我想在node.js应用程序内更新我的数据库,但它不工作。我console.log了参数,他们正确显示(即品牌,大小和用户电子邮件都是有效的和定义)。我如何完成这项工作?控制器内MongoDB没有在node.js应用程序中更新?

功能是被呼叫:

var User   = require('../models/user'); 

exports.addToFavs = function(req, res) { 
    var user=req.user; 
    var brandToFind = req.body.brand; 
    var size_result = req.body.size; 
    var email_user = user.local.email; 
    //res.send? local.email? 
    User.update({local: {email: email_user}} , {$set: { $push: { favorite_shoes: { brand: brandToFind, size: size_result}}}} , {multi : true}, function(error) { 
     if (error) console.log(error); 
     console.log('Added %s with size=%s', brandToFind, size_result); 
     console.log(User.find(email_user)); 
     res.redirect('/favorites'); 
    }) 
}; 

模式:

var userSchema = mongoose.Schema({ 
    local   : { 
     email  : String, 
     password  : String, 
    }, 
    favorite_shoes : [shoeSchema], 
    history: [searchSchema], 
}); 

var shoeSchema = mongoose.Schema({ 
    brand: String, 
    size: String, 
}); 

var searchSchema = mongoose.Schema({ 
    brand_original: String, 
    brand_result: String, 
    size: String, 
}); 
+0

我不使用猫鼬,但你shoeSchema和searchSchema应userSchema之前,因为'favorite_shoes:[shoeSchema]'是非常'favorite_shoes:[未定义]' – OneOfOne

+0

我这样做,它仍然无法正常工作。 – girlrockingguna

回答

1

你有一个在你的查找和突出的问题可能在另一台。该位是错误的:

User.update({local: {email: email_user}}, ... 

而且它是因为你指定这一点,是寻找与该local匹配exactly你正在询问一个文件的方式是错误的。换句话说,查找在子文档中也没有password字段的文档。你想要的是:

User.update({"local.email": email_user}, ... 

这与*匹配值在文档中匹配email场,无论什么附加字段是子文件内。有关更多信息,请阅读手册部分,直到熟悉各种查询表单。

http://docs.mongodb.org/manual/tutorial/query-documents/

第二潜在件事,可能从您发布的与您使用猫鼬的代码是立即明显。这是一个陷阱的未启动和仍然思维关系条款。

你展现模式定义,但除非你只使用一个模型(只是User),那么操作你正在尝试做的意愿工作。原因是,在单一模型表单中,那么您的相关模式被认为是embedded documents,它们适合您正在执行的更新操作。

但是,如果您已为shoeSchemasearchSchema中的每一个定义了模型,则这些文档实际上将在单独的集合中创建,并且此类更新将不起作用。

在后一种情况下,请回到documentation,熟悉概念,重新思考并重新实现您的逻辑。

相关问题