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

查看:166
本文介绍了如何在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);
mongoose.model('Contact', ContactSchema); //is this line superflous??
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. 如果我在模型上调用update:

    Contact.update({phone:request.phone},contact, {upsert:true},function(err {...})

    我进入了一些无限循环,因为Mongoose更新实现显然不需要object作为第二个参数。

  4. 如果我这样做,但在第二个参数中我传递了一个请求属性的关联数组 {status:request.status,电话:request.phone ...} 它有效 - 但后来我没有参考具体的联系人,也找不到它的 createdAt updatedAt properties。

  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.

所以底线,毕竟我试过:给定一个文件联系,如何更新它?存在,或者如果不存在则添加它?

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个DB调用而不是一个。

希望未来的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天全站免登陆