javascript - Mongoose 更新/更新?

标签 javascript node.js mongodb mongoose

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

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

我会继续玩弄它的。

最佳答案

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

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

关于javascript - Mongoose 更新/更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9661081/

相关文章:

javascript - 使用 AJAX 调用 php 函数一直失败

node.js - 错误 : no open connections at Db. _executeQueryCommand Node.js

javascript - 为什么我安装了node 10.1.0后显示安装的版本是5.6.0?

node.js - NodeJS/MongoDB 中集合的不同数据库

Mongodb聚合匹配查询,优先全匹配

javascript - 嵌套路由: How to query Rails DB and store values in JavaScript variables?

javascript - 按类别显示语义 UI React 搜索结果?

javascript - 刷新页面时,反冲不持久状态

node.js - 使用 yeoman 生成角度应用程序时出错 : unhandled Template render error

node.js - Node.js/Mongoose 上的 "VersionError: No matching document found"错误