首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose更新/更新?

Mongoose更新/更新?
EN

Stack Overflow用户
提问于 2012-03-12 10:33:36
回答 5查看 28.3K关注 0票数 10

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

代码语言:javascript
复制
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()的conditions部分进行OR运算

代码语言:javascript
复制
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(){});
};

我会继续摆弄它。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-03-12 11:58:46

代码语言:javascript
复制
var reg_handler = function (act) {
  UserModel.update({ $or: [{nick: act.nick}, {hmask: act.host}] }, { $set: { lastfm: act.params } }, { upsert: true }, function(){});
};

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

票数 15
EN

Stack Overflow用户

发布于 2013-09-06 22:18:05

使用'upsert‘选项设置为true的findOneAndUpdate

票数 9
EN

Stack Overflow用户

发布于 2012-03-12 11:25:09

这个怎么样(还没有测试,但应该可以使用最新的mongoose):

代码语言:javascript
复制
UserModel.findAndModify({nick: act.nick, hmask: act.host}, [], {$set: {lastfm: act.params}}, {}, callback);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9661081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档