如何更新猫鼬中的嵌入文档?

发布于 2024-11-29 02:40:05 字数 1686 浏览 0 评论 0原文

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

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

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

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

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 客户端调用:

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

运行:

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

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.

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

Here are the schemas:

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

which returns:

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

That should be the equivalent of this mongo client call:

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

Running:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

远昼 2024-12-06 02:40:05

当您已经拥有用户时,您可以执行以下操作:

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 查找文档。

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

* * warning * *

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

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) {
  // ...
});

as found here: http://mongoosejs.com/docs/subdocs.html

Finding a sub-document

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

* * warning * *

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.

失而复得 2024-12-06 02:40:05

这只是变量名称不匹配吗?

for 循环中有 user.userListings[i].listingId,但 find 中有 user.userListings[i]._id

您是在寻找 listingId 还是 _id

Is this just a mismatch on variables names?

You have user.userListings[i].listingId in the for loop but user.userListings[i]._id in the find.

Are you looking for listingId or _id?

甜心小果奶 2024-12-06 02:40:05

您必须保存父对象,并标记修改嵌套文档。

我们就是这样做的

exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Profile.findById(req.params.id, function (err, profile) {
    if (err) { return handleError(res, err); }
    if(!profile) { return res.send(404); }
    var updated = _.merge(profile, req.body);
    updated.markModified('NestedObj');
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, profile);
    });
  });
};

You have to save the parent object, and markModified the nested document.

That´s the way we do it

exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Profile.findById(req.params.id, function (err, profile) {
    if (err) { return handleError(res, err); }
    if(!profile) { return res.send(404); }
    var updated = _.merge(profile, req.body);
    updated.markModified('NestedObj');
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, profile);
    });
  });
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文