Mongoose update/upsert?

2019-01-23 18:11发布

问题:

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.

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

I will keep toying around with it.

回答1:

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

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



回答2:

Use findOneAndUpdate with the 'upsert' option set to true.



回答3:

How about this (haven't test, but should work with latest mongoose):

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


回答4:

first you need to define schema for particular collection

user schema:

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

use in code:

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


回答5:

You can use findOneAndUpdate() and need to set {new: true}. You can check the 4.0.0 release notes, according to which "new" is by default 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    
  });
);