问题描述
在Mongoose文档中的以下地址: http://mongoosejs.com/docs/embedded-documents.html
In the Mongoose documentation at the following address:http://mongoosejs.com/docs/embedded-documents.html
有一条声明:
请考虑以下代码段:
post.comments.id(my_id).remove();
post.save(function (err) {
// embedded comment with id `my_id` removed!
});
我已经查看了数据,但嵌入式文档没有 _id ,这似乎已由本帖子确认:
I've looked at the data and there are no _ids for the embedded documents as would appear to be confirmed by this post:
我的问题是:
文档是否正确?如果是这样,那么我如何找出"my_id"是什么(在示例中),以便首先执行'.id(my_id)'?
Is the documentation correct? If so then how do I find out what 'my_id' is (in the example) to do a '.id(my_id)' in the first place?
如果文档不正确,可以安全地将索引用作文档数组中的ID,或者我应该手动生成唯一的ID(根据所提到的内容).
If the documentation is incorrect is it safe to use the index as an id within the document array or should I generate a unique Id manually (as per the mentioned post).
推荐答案
不是对像这样的json对象(猫鼬文档建议的方式)进行push():
Instead of doing push() with a json object like this (the way the mongoose docs suggest):
// create a comment
post.comments.push({ title: 'My comment' });
您应该创建嵌入式对象的实际实例,并创建push()
.然后,您可以直接从中获取_id字段,因为猫鼬在实例化对象时对其进行设置.这是一个完整的示例:
You should create an actual instance of your embedded object and push()
that instead. Then you can grab the _id field from it directly, because mongoose sets it when the object is instantiated. Here's a full example:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var ObjectId = Schema.ObjectId
mongoose.connect('mongodb://localhost/testjs');
var Comment = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comment]
, meta : {
votes : Number
, favs : Number
}
});
mongoose.model('Comment', Comment);
mongoose.model('BlogPost', BlogPost);
var BlogPost = mongoose.model('BlogPost');
var CommentModel = mongoose.model('Comment')
var post = new BlogPost();
// create a comment
var mycomment = new CommentModel();
mycomment.title = "blah"
console.log(mycomment._id) // <<<< This is what you're looking for
post.comments.push(mycomment);
post.save(function (err) {
if (!err) console.log('Success!');
})
这篇关于猫鼬嵌入的文档/DocumentsArrays ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!