【问题标题】:Mongoose update/upsert?猫鼬更新/更新?
【发布时间】:2012-03-28 11:58:41
【问题描述】:

我查看了网站上的一些问题,但还没有完全弄清楚我做错了什么。我有一些这样的代码:

var mongoose = require('mongoose'),
db = mongoose.connect('mongodb://localhost/lastfm'),
Schema = mongoose.Schema,
User = new Schema({
  nick: String,
  hmask: String,
  lastfm: String
});
var UserModel = mongoose.model('User', User);

//Register user to mongodb
var reg_handler = function (act) {
// should add a new entry to the db if nick (act.nick) && hmask (act.host)
// aren't already in the db. Otherwise, update the entry that matches nick
// or hostmask with the new lastfm name (act.params)
};

var get_handler = function (act) {
  UserModel.find({ nick: act.params }, function (err, users) {
    if (err) { console.log(err) };
    users.forEach(function (user) {
      console.log('url for user is http://url/' + user.lastfm);
    });
  });
};

我不确定我应该在中间做什么才能让它正确更新数据库。我已经尝试了很多事情,但无法撤消以找出我尝试过的所有内容。它占用了我一夜的大部分时间,我希望它能够正常工作。

这几乎是我想要的,不知道有没有办法在.update()的条件部分做OR

var reg_handler = function (act) {
  var lfmuser = { nick: act.nick, hmask: act.host, lastfm: act.params };
  UserModel.update({ nick: act.nick }, { $set: lfmuser }, { upsert: true }, function(){});
};

我会继续玩弄它的。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    可以使用findOneAndUpdate(),需要设置{new: true}。 可以查看4.0.0 release notes,默认是“new” false.

    UserModel.findOneAndUpdate(
      { nick: act.nick },       //your condition for check
      { $set: lfmuser },       //new values you want to set
      { upsert: true, 'new': true }).exec(function (err, data){
          //your result    
      });
    );
    

    【讨论】:

      【解决方案2】:

      首先你需要为特定的集合定义模式

      用户架构:

      username: {type: String, required: true, upsert: true }

      在代码中使用:

      .findOne({ emailId: toEmail })
      .update({$set: { username: ravi }})
      .exec()
      

      【讨论】:

        【解决方案3】:

        使用 findOneAndUpdate 并将 'upsert' 选项设置为 true。

        【讨论】:

        • 在接受的答案中,这是否比Model.update() 更好(或更差)?
        • @joeytwiddle 我的建议是,如果您只想更新而不取回记录,则进行模型更新,否则,如果您想要恢复记录, findOneAndUpdate 将起作用。
        【解决方案4】:
        var reg_handler = function (act) {
          UserModel.update({ $or: [{nick: act.nick}, {hmask: act.host}] }, { $set: { lastfm: act.params } }, { upsert: true }, function(){});
        };
        

        这正是我想要的,它是一行。 :D 完美!

        【讨论】:

        • 您可能想为最后一个函数添加一些错误处理;)
        【解决方案5】:

        这个怎么样(还没有测试,但应该与最新的猫鼬一起工作):

        UserModel.findAndModify({nick: act.nick, hmask: act.host}, [], {$set: {lastfm: act.params}}, {}, callback);
        

        【讨论】:

        • 将对其进行测试,并最终使其与 .update() 一起使用。我不知道我以前做错了什么,但现在可以正常工作了。
        • 不,这会使它崩溃。将回答我最终开始工作的内容。
        猜你喜欢
        • 2016-05-14
        • 2016-05-24
        • 2020-11-13
        • 2019-01-23
        • 2015-04-10
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-14
        相关资源
        最近更新 更多