簡體   English   中英

貓鼬更新/ upsert?

[英]Mongoose update/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。

首先,您需要為特定集合定義模式

用戶架構:

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

在代碼中使用:

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

您可以使用findOneAndUpdate()並需要設置{new: true} 您可以查看4.0.0發行說明 ,默認情況下“new”默認為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    
  });
);

怎么樣(沒有測試,但應該使用最新的貓鼬):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM