如何更新猫鼬中的嵌入文档? [英] How to update embedded document in mongoose?

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

问题描述

我已经浏览了 mongoose API,以及很多关于 SO 和 google group 的问题,但仍然无法弄清楚更新嵌入式文档.

I've looked through the mongoose API, and many questions on SO and on the google group, and still can't figure out updating embedded documents.

我正在尝试用 args 的内容更新这个特定的 userListings 对象.

I'm trying to update this particular userListings object with the contents of args.

for (var i = 0; i < req.user.userListings.length; i++) {
    if (req.user.userListings[i].listingId == req.params.listingId) {
        User.update({
            _id: req.user._id,
            'userListings._id': req.user.userListings[i]._id
        }, {
            'userListings.isRead': args.isRead,
            'userListings.isFavorite': args.isFavorite,
            'userListings.isArchived': args.isArchived
        }, function(err, user) {
            res.send(user);
        });
    }
}

以下是架构:

var userListingSchema = new mongoose.Schema({
    listingId: ObjectId,
    isRead: {
        type: Boolean,
        default: true
    },
    isFavorite: {
        type: Boolean,
        default: false
    },
    isArchived: {
        type: Boolean,
        default: false
    }
});

var userSchema = new mongoose.Schema({
    userListings: [userListingSchema]
});

这个发现也不起作用,这可能是第一个问题:

This find also doesn't work, which is probably the first issue:

User.find({
    '_id': req.user._id,
    'userListings._id': req.user.userListings[i]._id
}, function(err, user) {
    console.log(err ? err : user);
});

返回:

{ stack: [Getter/Setter],
  arguments: [ 'path', undefined ],
  type: 'non_object_property_call',
  message: [Getter/Setter] }

这应该相当于这个 mongo 客户端调用:

That should be the equivalent of this mongo client call:

db.users.find({'userListings._id': ObjectId("4e44850101fde3a3f3000002"), _id: ObjectId("4e4483912bb87f8ef2000212")})

运行:

mongoose v1.8.1
mongoose-auth v0.0.11
node v0.4.10 

推荐答案

当您已经拥有用户时,您可以这样做:

when you already have the user, you can just do something like this:

var listing = req.user.userListings.id(req.params.listingId);

listing.isRead = args.isRead;
listing.isFavorite = args.isFavorite;
listing.isArchived = args.isArchived;

req.user.save(function (err) {
  // ...
});

在这里找到:http://mongoosejs.com/docs/subdocs.html

查找子文档

每个文档都有一个 _id.DocumentArrays 有一个特殊的 id 方法,用于通过 _id 查找文档.

Each document has an _id. DocumentArrays have a special id method for looking up a document by its _id.

var doc = parent.children.id(id);

* * 警告 * *

正如@zach 所指出的,您必须在实际文档的架构之前声明子文档的架构才能使用 id() 方法.

as @zach pointed out, you have to declare the sub-document's schema before the actual document 's schema to be able to use the id() method.

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

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