如何在 Mongoose 中更新/插入文档? [英] How do I update/upsert a document in Mongoose?

查看:58
本文介绍了如何在 Mongoose 中更新/插入文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是时候了,也许是我淹没在稀疏的文档中,无法理解在 Mongoose 中更新的概念:)

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 :)

交易如下:

我有一个联系模式和模型(缩短的属性):

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

现在我们遇到了问题:

  1. 如果我调用 contact.save(function(err){...}) 如果具有相同电话号码的联系人已经存在(如预期 - 唯一),我将收到错误消息
  2. 我无法调用 update() 联系方式,因为文档中不存在该方法
  3. 如果我调用模型的更新:
    Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})
    我陷入了某种无限循环,因为 Mongoose 更新实现显然不希望将对象作为第二个参数.
  4. 如果我也这样做,但在第二个参数中我传递了一个请求属性的关联数组 {status: request.status, phone: request.phone ...} 它可以工作 - 但是那么我就没有对特定联系人的引用,也无法找到它的 createdAtupdatedAt 属性.
  1. 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)
  2. I can't call update() on contact, since that method does not exist on a document
  3. 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.
  4. 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 its createdAt and updatedAt properties.

所以最重要的是,毕竟我尝试过:给定一个文档 contact,如果它存在,我如何更新它,或者如果它不存在,我如何添加它?

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?

感谢您的时间.

推荐答案

好吧,我等了很久还是没有答案.最后放弃了整个更新/upsert 方法并继续:

Well, I waited long enough and no answer. Finally gave up the whole update/upsert approach and went with:

ContactSchema.findOne({phone: request.phone}, function(err, contact) {
    if(!err) {
        if(!contact) {
            contact = new ContactSchema();
            contact.phone = request.phone;
        }
        contact.status = request.status;
        contact.save(function(err) {
            if(!err) {
                console.log("contact " + contact.phone + " created at " + contact.createdAt + " updated at " + contact.updatedAt);
            }
            else {
                console.log("Error: could not save contact " + contact.phone);
            }
        });
    }
});

有效果吗?是的.我对此满意吗?可能不是.2 个数据库调用而不是一个.
希望未来的 Mongoose 实现能够提供 Model.upsert 函数.

Does it work? Yep. Am I happy with this? Probably not. 2 DB calls instead of one.
Hopefully a future Mongoose implementation would come up with a Model.upsert function.

这篇关于如何在 Mongoose 中更新/插入文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆