猫鼬更新/upsert? [英] Mongoose update/upsert?

查看:41
本文介绍了猫鼬更新/upsert?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've looked at some of the questions on the site and haven't quite figured out what I'm doing wrong. I've some code like this:

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);
    });
  });
};

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

I'm not sure what I should be doing in the middle there to get it to update the database properly. I've tried quite a few things, can't undo to find out all what I've tried though. It's taken a large portion of my night and I want it working.

这几乎就是我想要的,不知道有没有什么办法可以在.update()

This is almost what I want, I wonder if there is any way to do an OR in the conditions part of the .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(){});
};

我会继续玩它.

推荐答案

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

这正是我想要的,而且只有一行.:D 完美!

This does exactly what I wanted, and it's one line. :D Perfect!

这篇关于猫鼬更新/upsert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆