問題:
Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :)也許是時候了,也許是我淹沒在稀疏的文檔中,無法理解 Mongoose 中更新的概念:)
Here's the deal:這是交易:
I have a contact schema and model (shortened properties):我有一個聯繫模式和模型(縮短的屬性):
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);
var Contact = mongoose.model('Contact', ContactSchema);
I receive a request from the client, containing the fields I need and use my model thusly:我收到來自客戶的請求,其中包含我需要的字段並因此使用我的模型:
mongoose.connect(connectionString);
var contact = new Contact({
phone: request.phone,
status: request.status
});
And now we reach the problem:現在我們遇到了問題:
- If I call
contact.save(function(err){...})
I'll receive an error if the contact with the same phone number already exists (as expected - unique)如果我撥打contact.save(function(err){...})
如果具有相同電話號碼的聯繫人已經存在(如預期 - 唯一),我將收到錯誤 - I can't call
update()
on contact, since that method does not exist on a document我無法在聯繫人中調用update()
,因爲文檔中不存在該方法 - If I call update on the model:如果我調用模型的更新:
Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})
I get into an infinite loop of some sorts, since the Mongoose update implementation clearly doesn't want an object as the second parameter.我進入了某種無限循環,因爲 Mongoose 更新實現顯然不想要一個對象作爲第二個參數。 - If I do the same, but in the second parameter I pass an associative array of the request properties
{status: request.status, phone: request.phone ...}
it works - but then I have no reference to the specific contact and cannot find out itscreatedAt
andupdatedAt
properties.如果我也這樣做,但在第二個參數中,我傳遞了一個請求屬性的關聯數組{status: request.status, phone: request.phone ...}
它可以工作 - 但是我沒有參考特定聯繫人和無法找出其createdAt
和updatedAt
性能。
So the bottom line, after all I tried: given a document contact
, how do I update it if it exists, or add it if it doesn't?所以最重要的是,畢竟我嘗試過:給定一個文檔contact
,如果它存在,我該如何更新它,或者如果它不存在,我如何添加它?
Thanks for your time.謝謝你的時間。
解決方案:
參考一: https://en.stackoom.com/question/UUVK參考二: https://stackoom.com/question/UUVK