目前正在为我的一个项目跟踪 Mongoose 和 MongoDB,但遇到一个 API 不清楚的部分.
Currently trailing out Mongoose and MongoDB for a project of mine but come across a segment where the API is not clear.
我有一个包含多个键和文档的模型,其中一个键称为 watchList.这是用户正在观看的一组 ID,但我需要确保这些值保持唯一.
I have a Model which contains several keys and documents, and one of those keys os called watchList. This is an array of ID's that the user is watching, But I need to be sure that these values stay unique.
这是一些示例代码:
var MyObject = new Mongoose.Schema({ //.... watching : {type: Array, required: false}, //.... });所以我的问题是如何确保推入数组的值只存储一个,从而使值唯一,我可以只使用 unique: true 吗?
So my question is how can I make sure that the values pushed into the array only ever store one, so making the values unique, can i just use unique: true ?
谢谢
推荐答案据我所知,在 mongoose 中执行此操作的唯一方法是调用底层 Mongo 操作符 (由 danmactough 提及).在猫鼬中,这看起来像:
To my knowledge, the only way to do this in mongoose is to call the underlying Mongo operator (mentioned by danmactough). In mongoose, that'd look like:
var idToUpdate, theIdToAdd; /* set elsewhere */ Model.update({ _id: idToUpdate }, { $addToSet: { theModelsArray: theIdToAdd } }, function(err) { /*...*/ } );注意:此功能需要猫鼬版本>= 2.2.2
Note: this functionality requires mongoose version >= 2.2.2