猫鼬更新/ upsert?

Rob*_*Rob 9 javascript mongoose mongodb node.js

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

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);
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

我不确定我应该在中间做什么来让它正确地更新数据库.我已经尝试了很多东西,无法撤消以找出我尝试过的所有内容.这是我晚上的很大一部分,我希望它工作.

这几乎是我想要的,我想知道是否有任何方法可以在条件部分进行OR .update()

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(){});
};
Run Code Online (Sandbox Code Playgroud)

我会继续玩弄它.

Rob*_*Rob 12

var reg_handler = function (act) {
  UserModel.update({ $or: [{nick: act.nick}, {hmask: act.host}] }, { $set: { lastfm: act.params } }, { upsert: true }, function(){});
};
Run Code Online (Sandbox Code Playgroud)

这正是我想要的,它是一条线.:D完美!

  • 您可能想要为最后一个函数添加一些错误处理;) (5认同)

mik*_*ana 9

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

  • 在接受的答案中,为什么这比"Model.update()"更好(或更糟)? (2认同)