Nasıl/upsert güncelleme Gelincik bir belge?
Belki zamanı, belki de seyrek belgeleri bana boğulma ve Firavun faresi:) güncelleme kavramı etrafında başımı sarmak için güçlü olmak değil
İşte anlaşma:
Kişi bir şema ve model (özellikleri kısaltılmış) var:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongooseTypes = require("mongoose-types"),
useTimestamps = mongooseTypes.useTimestamps;
var ContactSchema = new Schema({
phone: { type: String, index: { unique: true, dropDups: true } },
status: { type: String, lowercase: true, trim: true, default: 'on' }
});
ContactSchema.plugin(useTimestamps);
mongoose.model('Contact', ContactSchema); //is this line superflous??
var Contact = mongoose.model('Contact', ContactSchema);
İstemciden bir istek ve model benim gerçekten ihtiyacım var kullanım alanları içeren alıyorum:
mongoose.connect(connectionString);
var contact = new Contact({
phone: request.phone,
status: request.status
});
Ve şimdi sorunumuz ulaşmak:
- Eğer
contact.save(function(err){...})
ararsam eğer aynı telefon numarası ile temas zaten varsa bir hata eşsiz bir görev gibi kabul edeceğim - Güncelleme arayamam() yöntemi bir belge mevcut olmadığından başvurun
- Eğer model üzerinde güncelleme diyebilir miyim:
Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})
Gelincik update uygulaması, açıkça ikinci parametre olarak bir nesne istemiyor çünkü bir çeşit sonsuz döngüye alıyorum. - Eğer benim de benzer, ama ikinci parametre geçiyorum ilişkilendirilebilir bir dizi talep özellikleri
{status: request.status, phone: request.phone ...}
çalışır - ama ben hiçbir başvuru için belirli kişi ve öğrenmemeli onun createdAt ve updatedAt özellikleri.
Alt satırında, sonra denedim: contact
ne varsa onu güncellerim, ya da öyle olmasa bile bunu da ekleyelim mi? bir belge verildi
Zaman ayırdığınız için teşekkürler.
CEVAP
Sadece katı 3 saat sonra aynı sorunu çözmeye çalışırken yandı. Özellikle, "var, ya da başka türlü. eklerseniz" tüm belgeyi değiştirmek istedim İşte çözüm:
var contact = new Contact({
phone: request.phone,
status: request.status
});
// Convert the Model instance to a simple object using Model's 'toObject' function
// to prevent weirdness like infinite looping...
var upsertData = contact.toObject();
// Delete the _id property, otherwise Mongo will return a "Mod on _id not allowed" error
delete upsertData._id;
// Do the upsert, which works like this: If no Contact document exists with
// _id = contact.id, then create a new doc using upsertData.
// Otherwise, update the existing doc with upsertData
Contact.update({_id: contact.id}, upsertData, {upsert: true}, function(err{...});
an issue on the Mongoose project page Bu konuda bilgisi olan dokümanlar da eklenmesini talep oluşturdum.
Oracle: (nasıl Güncelleme ya da bir ta...
Nasıl düz bir nesne içine Gelincik bir...
Nasıl node.js güncelleme ve sonraki sü...
Hatayı düzeltmek için nasıl "Günc...
Nasıl düzgün S4 sınıfı yuvaları Roxyge...