mongoose更新/ upsert?

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

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完美!

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

怎么样(没有testing,但应该与最新的mongoose一起工作):

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

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

用户架构:

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

在代码中使用:

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

您可以使用findOneAndUpdate()并需要设置{new: true} 。 您可以检查4.0.0发行说明 ,根据哪个“新”默认为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 }); );