javascript - 如何在 Mongoose 中更新/插入文档?

标签 javascript mongodb node.js mongoose

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

这是交易:

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

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

我收到来自客户的请求,其中包含我需要的字段并因此使用我的模型:

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 属性。

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

感谢您的宝贵时间。

最佳答案

Mongoose 现在原生支持 findOneAndUpdate (调用 MongoDB findAndModify )。

upsert = true 选项会在对象不存在时创建它。 默认为 false

var query = {'username': req.user.username};
req.newData.username = req.user.username;

MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
    if (err) return res.send(500, {error: err});
    return res.send('Succesfully saved.');
});

在旧版本中,Mongoose 不支持使用此方法的这些钩子(Hook):

  • 默认值
  • 二传手
  • 验证器
  • 中间件

关于javascript - 如何在 Mongoose 中更新/插入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7267102/

相关文章:

javascript - 操作 JS 对象

javascript - 如何从固定字符串中删除字符

MongoDB db.getCollection.find 和db.tablename.find 的区别?

MongoDB $redact 过滤掉数组的一些元素

node.js - webpack 构建时缺少绑定(bind)/myproject/node_modules/node-sass/vendor/linux-x64-57/binding.node

javascript - Meteor.js - 如何在登录时重新呈现模板

javascript - 是否可以通过javascript/html/css在JPEG图像的某个地方添加两个电话号码作为链接

javascript - 打印 javascript 阻止我的链接

node.js - 使用 mongoose 返回包含某个字段的所有文档

javascript - 如何将 SSL 证书添加到我现有的 node.js 服务器?